LeetCode算法#257二进制树路径



针对LeetCode算法问题#257二进制树路径。我知道我们可以使用空字符串path来连接节点值,但为什么当我尝试使用列表path来存储节点值时,我也总是得到像[[1,2,5,3],[1,2,5,3]]这样的输出?

代码:

class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
# dfs

res = []
def helper(node, path):

if not node: return 

#path+=str(node.val)
path.append(node.val)
# leaf node
if not node.left and not node.right:
res.append(path)
#return
#path += '->'  
helper(node.left, path)
helper(node.right, path)
helper(root, [])
return res

测试用例:[1,2,3,null,5]

您正在将对同一path列表的引用传递给两个递归调用,因此追加这些调用(以及每个递归调用(将追加到同一列表。

Something Related—";最小惊奇";和可变默认自变量

字符串是不可变的。更改字符串会返回一个新引用,因此解决方案可以使用字符串。

最新更新