【发布时间】:2021-04-16 14:51:48
【问题描述】:
我有一个问题是要找到总和的所有路径。问题是:
给定一棵二叉树和一个数字“S”,找到从根到叶的所有路径,使得每条路径的所有节点值之和等于“S”。
我的递归方法是:
def all_sum_path(root, target):
result = []
find_sum_path(root, target, result, [])
return result
def find_sum_path(root, target, result, new_path):
if not root:
return None
new_path.append(root.value)
diff = target - root.value
if not root.left and not root.right and diff == 0:
# copy the value of the list rather than a reference
result.append(list(new_path))
if root.left:
return find_sum_path(root.left, diff, result, new_path)
if root.right:
return find_sum_path(root.right, diff, result, new_path)
del new_path[-1]
class TreeNode():
def __init__(self, _value):
self.value = _value
self.left, self.right, self.next = None, None, None
def main():
root = TreeNode(1)
root.left = TreeNode(7)
root.right = TreeNode(9)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(2)
root.right.right = TreeNode(7)
print(all_sum_path(root, 12))
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print(all_sum_path(root, 23))
main()
输出是:
[[1, 7, 4]]
[[12, 7, 4]]
Process finished with exit code 0
但是,正确的做法应该是:
def all_sum_path(root, target):
result = []
find_sum_path(root, target, result, [])
return result
def find_sum_path(root, target, result, new_path):
if not root:
return None
new_path.append(root.value)
diff = target - root.value
if not root.left and not root.right and diff == 0:
# copy the value of the list rather than a reference
result.append(list(new_path))
if root.left:
find_sum_path(root.left, diff, result, new_path)
if root.right:
find_sum_path(root.right, diff, result, new_path)
del new_path[-1]
class TreeNode():
def __init__(self, _value):
self.value = _value
self.left, self.right, self.next = None, None, None
def main():
root = TreeNode(1)
root.left = TreeNode(7)
root.right = TreeNode(9)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(2)
root.right.right = TreeNode(7)
print(all_sum_path(root, 12))
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print(all_sum_path(root, 23))
main()
有输出:
[[1, 7, 4], [1, 9, 2]]
[[12, 7, 4], [12, 1, 10]]
Process finished with exit code 0
我在这里有一些问题:
-
为什么我们在递归语句中不需要
return?我也对return语句如何将输出减少到只有一个感兴趣? -
为什么我们不需要
result = find_sum_path(root, target, result, [])?那么更新结果背后的逻辑是什么? -
不知道为什么时间复杂度是O(N^2)?
上述算法的时间复杂度为O(N^2),其中‘N’是树中节点的总数。这是因为我们遍历每个节点一次(这将花费 O(N)),并且对于每个叶节点,我们可能必须存储它的路径,这将花费 O(N)。
提前感谢您的帮助。
【问题讨论】:
标签: python recursion return binary-tree