Leetcode 112. Path Sum

这篇博客介绍了一种使用递归算法解决二叉树中根到叶节点路径和等于目标值的问题。代码实现了一个名为`Solution`的类,包含`hasPathSum`方法,通过递归函数`test`检查是否存在满足条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Algorithm

Recursion. Divide the tree into two sub-trees find the sum-root.val in each one.

Code

# 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
        
        def test(root, sum_val):
            if not root:
                return sum_val == 0
            
            if not root.left and not root.right:
                return sum_val == root.val
            
            if root.left and test(root.left, sum_val-root.val):
                return True
            
            if root.right and test(root.right, sum_val-root.val):
                return True
            
            return False
        
        return test(root, targetSum)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值