题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
class Solution:
def __init__(self):
self.onepath=[]
self.patharray=[]
def FindPath_1(self,root,expectnumber):
if root is None:
return []
self.onepath.append(root.val)
expectnumber-=root.val
if expectnumber==0 and not root.left and not root.right:
self.patharray.append(self.onepath[:])
elif expectnumber>0:
self.FindPath_1(root.left,expectnumber)
self.FindPath_1(root.right,expectnumber)
self.onepath.pop()
return self.patharray
def FindPath_2(self, root, expectNumber):
# write code here
if not root:
return []
if root and not root.left and not root.right and root.val==expectNumber:
return [[root.val]]
res = []
left = self.FindPath(root.left,expectNumber-root.val)
print(left)
right = self.FindPath(root.right,expectNumber-root.val)
print(right)
for i in left+right:
res.append([root.val]+i)
return res
pNode1=TreeNode(10)
pNode2=TreeNode(5)
pNode3=TreeNode(12)
pNode4=TreeNode(4)
pNode5=TreeNode(7)
pNode1.left=pNode2
pNode1.right=pNode3
pNode2.left=pNode4
pNode2.right=pNode5
s=Solution()
s.FindPath_1(pNode1,22)