题目
我的方法
思路
用栈的方法遍历二叉树。
- 每次遍历一个数,将它的值加在temp中,同时判断
sum(temp)==target
是否成立,再看该节点是否是叶子节点,如果二者都成立,则将temp加入到路径结果中 - 每次遍历完一个节点的子树后,将该节点从栈中弹出的同时,也将节点的值从temp中弹出
- 主要是在前序遍历的基础上改的。不能用简易版的前序遍历,根节点比右孩子提前弹出,导致路径不完整,结果不正确。
sum(temp)==target
成立时,不能直接用result.append(temp)
,后面temp
改动,result
也会跟着改动。使用result.append(temp.copy())
或result.append(list(temp))
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, target: int):
if not root:return []
stack = []
result = []
temp = []
last_visit = root
while stack or root:
while root:
stack.append(root)
temp.append(root.val)
if sum(temp)== target and ( not(root.left or root.right)):
# print(temp)
result.append(temp.copy())
# print(result)
root = root.left
root = stack[-1]
if root.right != last_visit:
root = root.right
if not root:
last_visit = None
else:
temp_root = stack.pop()
temp.pop()
# print(temp_root.val)
last_visit = temp_root
root = None
return result
参考解法
通过设置全局遍历,用递归的方法实现
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, path = [], []
def recur(root, tar):
if not root: return
path.append(root.val)
tar -= root.val
if tar == 0 and not root.left and not root.right:
res.append(list(path))
recur(root.left, tar)
recur(root.right, tar)
path.pop()
recur(root, sum)
return res
作者:jyd
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/mian-shi-ti-34-er-cha-shu-zhong-he-wei-mou-yi-zh-5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。