题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:
其实就是深度优先遍历,到达叶子结点时判断target是否为零,注意每次递归一轮时需要回溯。
solution
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.list = []
self.list1 = []
def FindPath(self, root, expectNumber):
if root == None:
return self.list1
# print('********')
self.list.append(root.val)
# print(list)
expectNumber -= root.val
# print('----', target)
if expectNumber == 0 and root.left == None and root.right == None:
newlist = []
for line in self.list:
newlist.append(line)
self.list1.append(newlist)
# print('*****', list1)
# list1.append(proot.val)
# print(list1)
# print(list)
# print('********')
# print(proot.val)
# print('********')
self.FindPath(root.left, expectNumber)
self.FindPath(root.right, expectNumber)
self.list.pop()
return self.list1