1、使用 BFS(广度优先搜索)的方法实现计算根节点到每个子节点的和,知道最后的叶子节点,判断和是否为指定的值
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
# 使用队列存储当前节点和根节点到当前节点的和
node_queue = [root]
sum_queue = [root.val]
while node_queue:
node, current_sum = node_queue.pop(0), sum_queue.pop(0)
# 判断当前节点是不是叶子结点,如果是,则判断是否符合条件
if node.left is None and node.right is None:
if current_sum == sum:
return True
else:
continue
# 判断左子树是否存在
if node.left:
node_queue.append(node.left)
sum_queue.append(current_sum + node.left.val)
# 判断右子树是否存在
if node.right:
node_queue.append(node.right)
sum_queue.append(current_sum + node.right.val)
return False
2、使用递归的方式求路径的和,路径和可以分为当前节点的值以及其子树的路径和,利用这种迭代求路径和
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
if not root.left and not root.right:
if sum == root.val:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)