[英]Binary Tree Path Sum (python)
Please check my code. 请检查我的代码。 I can't find where is the bug.
我找不到错误在哪里。 The question is here .
问题在这里 。
Here is my solution: 这是我的解决方案:
# Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
#
# A valid path is from root node to any of the leaf nodes.
# Example
# Given a binary tree, and target = 5:
#
# 1
# / \
# 2 4
# / \
# 2 3
# return
#
# [
# [1, 2, 2],
# [1, 4]
# ]
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root the root of binary tree
# @param {int} target an integer
# @return {int[][]} all valid paths
result = []
def binaryTreePathSum(self, root, target):
# Write your code here
if root is None:
return self.result
self.dfs(root, [], target)
return self.result
def dfs(self, node, tmp, target):
tmp.append(node.val)
if node.left is None and node.right is None:
if target == sum(tmp):
#print tmp
self.result.append(tmp)
tmp.pop()
return
if node.left:
self.dfs(node.left, tmp, target)
if node.right:
self.dfs(node.right, tmp, target)
tmp.pop()
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(2)
root.left.right = TreeNode(3)
root.right = TreeNode(4)
result = Solution().binaryTreePathSum(root, 5)
print result
Let assume the input is {1,2,4,2,3}, 5
. 假设输入为
{1,2,4,2,3}, 5
。 After running the solution, the output is [[],[]]
. 运行解决方案后,输出为
[[],[]]
。 But if I unindent the print tmp
, the output will be 但是如果我取消缩进
print tmp
,输出将是
[1, 2, 2]
[1, 4]
[[],[]]
The output of tmp
is correct. tmp
的输出正确。 But it seems that result.append(tmp)
didn't append the tmp
into result
. 但是似乎
result.append(tmp)
没有将tmp
附加到result
。 I don't know where is the problem. 我不知道问题出在哪里。
The problem is that your result
list contains one and the same list multiple times . 问题是您的
result
列表多次包含一个和同一列表 。
You're appending the tmp
list to result
like so: 您将添加
tmp
列表以得到如下result
:
self.result.append(tmp)
And then you're mutating that very same list with tmp.pop()
and tmp.append(...)
. 然后,您将使用
tmp.pop()
和tmp.append(...)
对相同的列表进行tmp.pop()
。 That's why in the end, all your results are empty lists. 这就是为什么最终所有结果都是空列表的原因。
The solution is simple, just create a copy of your list: 解决方案很简单,只需创建列表的副本即可:
self.result.append(tmp[:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.