题目:输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
#defination of a Tree
class TreeNode:
def __init__(self,value=None,left=None,right=None):
self.val=value
self.left=left
self.right=right
class Solution:
def __init__(self):
self.list = []
self.list1 = []
def FindPath(self, root, expectNumber):
if root == None:
return self.list1
self.list.append(root.val)
print(expectNumber)
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(self.list)
print(expectNumber)
self.FindPath(root.left, expectNumber)
self.FindPath(root.right, expectNumber)
self.list.pop()
return self.list1
if __name__=="__main__":
head=TreeNode(4,TreeNode(2,TreeNode(1),TreeNode(3)),TreeNode(5,right=TreeNode(7,TreeNode(6))))
su=Solution()
num=0
k=1
total=9
# su.findkmax(head,5)
sss=su.FindPath(head,total)
print(sss)
# print('*'*20)
# su.middleReadStack(head)
# print('*' * 20)
# su.afterReadStack(head)