很简单的DFS,但是不知道为何sum嵌套函数找不到变量?
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root:TreeNode, expectNumber:int):
res,path=[],[]
def dfs(root,good):
if not root:return None
good+=root.val
path.append(root)
if not root.left and not root.right and good==expectNumber:res.append(path+[])
if root.left:dfs(root.left,good)
if root.right:dfs(root.right,good)
good-=root.val
path.pop()
dfs(root,0)
return res
# def FindPath(self, root, expectNumber):
# def dfs(root):
# sum += root.val
# path.append(root)
# if not root.left and not root.right and sum == expectNumber: res.append(path + [])
# if root.left: dfs(root.left)
# if root.right: dfs(root.right)
# sum -= root.val
# path.pop()
#
# res, path, sum = [], [], 0
# dfs(root)
# # return res
网友评论