题目:
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
解答:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
self.rlist = []
self.stack = []
# write code here
if root == None or expectNumber == 0:
return self.rlist
self.find(root, expectNumber)
return self.rlist
def find(self, root, expectNumber):
self.stack.append(root.val)
if expectNumber == root.val and root.left == None and root.right == None:
self.rlist.append(list(self.stack))
if root.left:
self.find(root.left, expectNumber - root.val)
if root.right:
self.find(root.right, expectNumber - root.val)
if self.stack:
self.stack.pop()
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
if root == None or expectNumber == 0:
return []
self.rlist = []
self.find([], root, expectNumber)
return self.rlist
def find(self, path, root, expectNumber):
if sum(path) + root.val == expectNumber and root.left == None and root.right == None:
path.append(root.val)
self.rlist.append(path)
return
if sum(path) + root.val < expectNumber:
path.append(root.val)
if root.left:
self.find(list(path), root.left, expectNumber)
if root.right:
self.find(list(path), root.right, expectNumber)
return