思路一:DFS
如果为叶子节点且总和为target,返回True,否则递归接着遍历
# 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 hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
return self.dfs(root,0,targetSum)
def dfs(self,root,plus,targetSum):
if root is None:
return False
plus+=root.val
if plus==targetSum and root.left is None and root.right is None:
return True
return self.dfs(root.left,plus,targetSum) or self.dfs(root.right,plus,targetSum)
简洁写法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
if not root.left and not root.right:
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
思路二:BFS
BFS 使用 队列 保存遍历每个节点以及到这个节点的路径和(path),如果该节点恰好是叶子节点,并且 路径和 正好等于 sum,返回true,否则不断把树上的节点压入队列循环判断。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
que = collections.deque()
que.append((root, root.val))
while que:
node, path = que.popleft()
if not node.left and not node.right and path == sum:
return True
if node.left:
que.append((node.left, path + node.left.val))
if node.right:
que.append((node.right, path + node.right.val))
return False