输入一棵二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 # 返回二维列表,内部每个列表表示找到的路径 9 def __init__(self): 10 self.list = [] 11 self.temp = [] 12 13 def preOrder(self,root,expectNumber): 14 if root != None: 15 self.temp.append(root.val) 16 self.preOrder(root.left,expectNumber) 17 self.preOrder(root.right,expectNumber) 18 if root.left == None and root.right == None: 19 sums = sum(self.temp) 20 if sums == expectNumber: 21 self.list.append(self.temp[:]) 22 self.temp.pop(-1) 23 def FindPath(self, root, expectNumber): 24 self.preOrder(root,expectNumber) 25 self.list = sorted(self.list,key=lambda l:-len(l)) 26 return self.list 27 # write code here