题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
解答
递归法
# coding:utf-8class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if root == None:
return []
result = []
self.sums = expectNumber
self.Sums(root, result, [root.val])
return result
def Sums(self, root, result, path):
if root.left == None and root.right == None and sum(path) == self.sums:
result.append(path)
if root.left:
self.Sums(root.left, result, path + [root.left.val])
if root.right:
self.Sums(root.right, result, path + [root.right.val])
结束!