题目要求:
输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。
此处路径定义为:从根节点开始,往下一直到一个叶节点,其所经过的所有节点所形成的路径
要点:
1.路径的保存
2.二叉树的遍历
3.是否考虑节点为负值或0
代码:(递归实现)
# coding=utf-8
"""
question:
输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。
路径定义为从树的根节点开始往下一直到叶节点所经过的节点所形成的路径。
"""
# 节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left_child = None
self.right_child = None
# 在根节点为 root 的树中寻找和为 n 的路径
def find_sum_path(root, n):
ret = [] # 答案路径列表
# 在根节点为 root 的树中寻找和为 n 的路径,以前的路径为 path
# 这里讨论的算法是树的所有节点的值都是正数
def find_path(root, path, n):
path.append(root.val) # 当前节点加入路径
if root.val > n: # 节点值已经大于 n,无解,若考虑负数,此分支不应存在
pass
elif root.val == n and root.left_child is None and root.right_child is None: # 解路径
ret.append(path.copy())
else:
if root.left_child: # 遍历左子树
find_path(root.left_child, path, n - root.val)
if root.right_child: # 遍历右子树
find_path(root.right_child, path, n - root.val)
path.pop() # 当前节点从路径删除
find_path(root, [], n)
return ret
if __name__ == '__main__':
# 构造一棵树
"""
10
6 15
11 20
9
"""
l = [6, 9, 10, 11, 15, 20]
t = []
for i in l:
t.append(TreeNode(i))
t[2].left_child = t[0]
t[2].right_child = t[4]
t[4].left_child = t[3]
t[4].right_child = t[5]
t[3].left_child = t[1]
# 测试
print(find_sum_path(t[2], 36))
print(find_sum_path(t[2], 16))
print(find_sum_path(t[2], 45))