113 路徑總和

2021-09-29 20:01:35 字數 2122 閱讀 7537

難度:中等

題目描述:

思路總結:這題看到以後,就是和上一題做法一樣,只要每次都記錄val值就好了。但是做的時候才發現遞迴方法每次返回的path陣列,會更新當前的路徑陣列,所以左右每次遞迴需要傳進去當前path陣列的copy。

題解一:

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution

:def

pathsum

(self, root: treenode,

sum:

int)

-> list[list[

int]]:

#思路:這題不知道為什麼是中等,以後還是不要管難易程度,以防思維陷入僵局

ifnot root:

return

res =

defhelper

(node, cur_sum, cur_path)

: cur_sum += node.val

ifnot node.left and

not node.right:

if cur_sum ==

sum:

if node.left:

helper(node.left, cur_sum, cur_path.copy())

if node.right:

helper(node.right, cur_sum, cur_path.copy())

helper(root,0,

)return res

題解一結果:

題解二:(迭代)

這裡用的112.路徑總和迭代思路的改進

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution

:def

pathsum

(self, root: treenode,

sum:

int)

-> list[list[

int]]:

#思路:這題不知道為什麼是中等,以後還是不要管難易程度,以防思維陷入僵局

ifnot root:

return

res =

stack =

[(root,

sum-root.val,

[root.val])]

while stack:

cur, last, path = stack.pop()if

not cur.left and

not cur.right and last ==0:

if cur.left:

tmp = path.copy(

)(cur.left, last-cur.left.val, tmp)

)if cur.right:

tmp = path.copy(

)(cur.right, last-cur.right.val, tmp)

)return res

題解二結果:

113 路徑總和

給定乙個二叉樹和乙個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。說明 葉子節點是指沒有子節點的節點。示例 給定如下二叉樹,以及目標和 sum 22,5 4 8 11 13 4 7 2 5 1返回 5,4,11,2 5,8,4,5 這次題目是112路徑總和的高階版,我們需要找到所有...

113 路徑總和 II

給定乙個二叉樹和乙個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。說明 葉子節點是指沒有子節點的節點。示例 給定如下二叉樹,以及目標和 sum 22,4 8 11 13 4 7 2 5 1 返回 5,4,11,2 5,8,4,5 definition for a binary tr...

113 路徑總和 II

給定乙個二叉樹和乙個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。說明 葉子節點是指沒有子節點的節點。示例 給定如下二叉樹,以及目標和 sum 22,definition for a binary tree node.class treenode object def init s...