1、递归
# 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:
# 空节点
if not root:
return False
# 叶子节点
if not root.left and not root.right:
return targetSum == root.val
# 每搜索一个节点从sum中减去节点值
return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val)
2、广度优先搜索
使用两个队列:
# 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:
if not root:
return False
# 两个队列,一个存节点,一个存根节点到此节点的节点值之和
que_node = collections.deque([root])
que_val = collections.deque([root.val])
while que_node:
node = que_node.popleft()
nodeval = que_val.popleft()
if not node.left and not node.right:
if nodeval == targetSum:
return True
if node.left:
que_node.append(node.left)
que_val.append(nodeval+node.left.val)
if node.right:
que_node.append(node.right)
que_val.append(nodeval+node.right.val)
return False
一个队列:
# 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:
if not root:
return False
# 一个队列存节点以及根节点到此节点的和
que_node = collections.deque([(root,root.val)])
while que_node:
node,nodeval = que_node.popleft()
if not node.left and not node.right:
if nodeval == targetSum:
return True
if node.left:
que_node.append((node.left,nodeval+node.left.val))
if node.right:
que_node.append((node.right,nodeval+node.right.val))
return False