输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
下图的二叉树有两条和为 22 的路径:10, 5, 7 和 10, 12

解题思路
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
res = []
if not root:
return res
self.target = expectNumber
self.dfs(root, res, [root.val])
return res
def dfs(self, root, res, path):
# 和大于要求的整数,则直接换路搜索
if sum(path)>self.target:
return
if not root.left and not root.right and sum(path) == self.target:
res.append(path)
if root.left:
self.dfs(root.left, res, path + [root.left.val])
if root.right:
self.dfs(root.right, res, path + [root.right.val])