可以通过二叉树的前序遍历,用一个stack来保存当前遍历的路径,遇到叶结点时判断是否和对应的值(expectNumber-该结点前路径之和)相等。注意stack的出栈时机。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import copy
class Solution:
def __init__(self):
self.ans=[]
self.stack=[]
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
def pathSum(root,expectNumber):
val=root.val
self.stack.append(val)
if root.left:
pathSum(root.left,expectNumber-val)
if root.right:
pathSum(root.right,expectNumber-val)
if not root.left and not root.right:
if val==expectNumber:
self.ans.append(copy.deepcopy(self.stack))
self.stack.pop()
return
if not root:
return []
pathSum(root,expectNumber)
return self.ans