输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
注意说stack类似指针存储的,相当于全局的,要pop,cursum只是局部的,不用减去。。stack要深拷贝进res,否则res中的也会被pop掉。
class Solution:
def FindPath(self, root, expectNumber):
if not root:
return []
cursum = 0
expect = expectNumber
res = []
stack = []
self.Findpp(root, cursum, stack, expect, res)
return res
def Findpp(self, root, cursum, stack, expect, res):
cursum += root.val
stack.append(root.val)
if(cursum == expect and root.left == None and root.right == None):
a = copy.deepcopy(stack)
res.append(a) #或者res.append(stack[:])
if root.left:
self.Findpp(root.left, cursum, stack, expect, res)
if root.right:
self.Findpp(root.right, cursum, stack, expect, res)
stack.pop()