JZ24 二叉树中和为某一值的路径
my version
错误记录
- 复制内容时,注意是否为引用
self.ret.append(copy.deepcopy(path))
由于这里的path
是引用,因此如果直接self.ret.append(path)
之后随着path
改变,self.ret
中的值也会跟着改变
import copy
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def __init__(self):
self.ret = []
def dfs(self, path, node, except_n):
path.append(node.val)
# print(path)
if sum(path) > except_n:
return
if not node.left and not node.right:
# 叶子节点
if sum(path) == except_n:
self.ret.append(copy.deepcopy(path))
return
if node.left:
self.dfs(path, node.left, except_n)
path.pop()
if node.right:
self.dfs(path, node.right, except_n)
path.pop()
def FindPath(self, root, expectNumber):
if not root or not expectNumber:
return
path = []
self.dfs(path, root, expectNumber)
return self.ret