题目描述
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
样例
给定一个二叉树,和 目标值 = 5:
1
/ \
2 4
/ \
2 3
返回:
[
[1, 2, 2],
[1, 4]
]
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @param {TreeNode} root the root of binary tree
# @param {int} target an integer
# @return {int[][]} all valid paths
def __init__(self):
self.ans = []
self.s = []
# 递归解法
def binaryTreePathSum(self, root, target):
# Write your code here
if root is None:
return self.ans
self.s.append(root.val)
target -= root.val
if target == 0 and root.left is None and root.right is None:
self.ans.append(list(self.s)
self.binaryTreePathSum(root.left, target)
self.binaryTreePathSum(root.right, target)
self.s.pop()
return self.ans
# 非递归解法
def binaryTreePathSum1(self, root, target):
# Write your code here
s = []
res = []
top = -1
sum = 0
p = root
while True:
while p is not None:
sum += p.val
s.append(p)
top += 1
p = p.left
f = True
q = None
while top != -1 and f :
p = s[-1]
if p.right == q:
if p.right is None and p.left is None and sum == target:
t = []
for i in s:
t.append(i.val)
res.append(t)
sum -= p.val
top -= 1
s.pop()
q = p
else:
p = p.right
f = False
if top == -1:
break
return res
在给定的二叉树中寻找所有节点和等于目标值的路径。有效路径需从根节点到叶节点。
3万+

被折叠的 条评论
为什么被折叠?



