题目:
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
解答:
方法一:递归
# 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 traversal(self,root,path,count,res):
if (not root.left) and (not root.right) and count==0:
res.append(path[::])
return
if root.left:
path.append(root.left.val)
self.traversal(root.left,path,count-root.left.val,res)
path.pop()
if root.right:
path.append(root.right.val)
self.traversal(root.right,path,count-root.right.val,res)
path.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res=[]
if not root:
return []
self.traversal(root,[root.val],targetSum-root.val,res)
return res
方法二:迭代
# 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 traversal(self,root,path,count,res):
if (not root.left) and (not root.right) and count==0:
res.append(path[::])
return
if root.left:
path.append(root.left.val)
self.traversal(root.left,path,count-root.left.val,res)
path.pop()
if root.right:
path.append(root.right.val)
self.traversal(root.right,path,count-root.right.val,res)
path.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res=[]
if not root:
return []
#stack记录:当前节点,当前路径值(根节点到当前节点的路径值),当前路径和
stack=[(root,[root.val],root.val)]
while stack:
cur,tmp,total=stack.pop()
if (not cur.left) and (not cur.right) and total==targetSum:
res.append(tmp)
if cur.right:
tmp.append(cur.right.val)
stack.append((cur.right,tmp[::],total+cur.right.val))
tmp.pop()
if cur.left:
tmp.append(cur.left.val)
stack.append((cur.left,tmp[::],total+cur.left.val))
tmp.pop()
return res