LeetCode112. Path Sum(Easy)

本文解析LeetCode路径总和问题,介绍两种有效算法实现:先序遍历递归和简化递归方法,帮助理解如何判断二叉树中是否存在从根节点到叶子节点的路径,使得沿途节点值之和等于给定目标值。

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

原题地址:https://leetcode.com/problems/path-sum/description/


题目描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.


题解:
先序遍历也是二叉树上的一种DFS, 这道题就直接按先序遍历的顺序,用一个变量存储累加值,和sum比较如果相等就返回True。
在向下一层遍历时使用了if (hasPathSum(root->left, sum)) return true这样的格式,可以保证只在返回True时才一路返回到最顶层,而在返回False时只回到上一层,当所有节点遍历完之后再返回False。于是代码如下:

class Solution {
public:
    int sums = 0;
    bool hasPathSum(TreeNode* root, int sum) {
        if (root != NULL) sums += root->val;
        else return false;
        if (sums == sum&&root->left == NULL&&root->right == NULL) return true;
        if (root->left != NULL) if (hasPathSum(root->left, sum)) return true;
        if (root->right != NULL) if (hasPathSum(root->right, sum)) return true;
        if (root != NULL) sums -= root->val;
        return false;
    }
};

114 / 114 test cases passed.
Status: Accepted
Runtime: 13 ms


再看其他人的算法,思路大致都一样,但是在处理方式上有更简单的表达,那就是在每向下一层遍历时,用sum减去当前节点的值,当sum等于当前叶子节点的值后,就找到了路径。这样避免了创建一个新的参数保存每一层累加的值,且不需要每次返回上一层时再将当前节点的值减去。
代码如下:


class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == NULL) return false;
        if (root->val == sum&&root->left == NULL&&root->right == NULL) return true;
        sum -= root->val;
        return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
    }
};

114 / 114 test cases passed.
Status: Accepted
Runtime: 9 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值