【发布时间】:2022-01-26 01:26:49
【问题描述】:
AllPaths() 上面的函数将包含二叉树每个叶子的路径的数组附加到全局数组 res。
代码工作得很好,但我想删除全局变量 res 并让函数返回一个数组。我该怎么做?
class Node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
res = []
def allPaths(node, arr=[]):
if node:
tmp = [*arr, node.value]
if not node.left and not node.right: # Leaf
res.append(tmp)
allPaths(node.left, tmp)
allPaths(node.right, tmp)
root = Node(1)
root.left = Node(2);
root.left.left = Node(4);
root.left.right = Node(5);
root.right = Node(3);
root.right.right = Node(6);
"""
1 <-- root
/ \
2 3
/ \ \
4 5 6 <-- leaves
"""
allPaths(root)
print(res)
# Output : [[1, 2, 4], [1, 2, 5], [1, 3, 6]]
【问题讨论】:
-
请注意,您可以直接使用
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))构建树
标签: python algorithm tree binary-tree