上述函数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]]