【leetcode】【easy】112. Path Sum

本文详细解析了LeetCode中路径总和问题的两种解法:非递归的栈方法与递归方法。通过具体示例展示了如何利用深度优先搜索(DFS)思想解决二叉树中寻找从根节点到叶子节点路径的问题,使其路径上所有数值之和等于给定的数值。

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

112. Path Sum

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.

Note: A leaf is a node with no children.

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.

题目链接:https://leetcode-cn.com/problems/path-sum/

 

思路

利用DFS的思想。

法一:非递归,栈

注意几个小陷阱:

1)树中有负数,因此一定要走到叶节点才能判定最后sum是否符合要求,无法在中途提前结束sum的计算。

特殊样例:

[-2,null,-3]
-5

2)由于sum的值是逐层累加的,因此在回溯时,也要逐层减去每个父节点的值,不能像普通的树遍历那样,跨层回到上一节点。在出栈时不能立刻弹出元素,若还需要再次取同一元素的话,可以加一个用于标记的空节点来帮助判断是否第一次取出。

特殊样例:

[1,-2,-3,1,3,-2,null,-1]
3

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        stack<TreeNode*> q;
        q.push(root);
        int cur = 0;
        while(!q.empty()){
            auto tmp = q.top();
            if(!tmp){
                q.pop();
                cur -= (q.top()->val);
                q.pop();
                continue;
            }
            cur += (tmp->val);
            if(!tmp->left && !tmp->right){
                if(cur==sum) return true;
                else{
                    cur -= (tmp->val);
                    q.pop();
                    continue;
                }
            } 
            else{
                q.push(NULL);
                if(tmp->right) q.push(tmp->right);
                if(tmp->left) q.push(tmp->left);
            }
        }
        return false;
    }
};

法二:递归

一开始思考递归想了五分钟也没想出来,一直想要找个办法把根节点到当前的累计sum向下传递 or 向上回传。后来做完非递归,突然就想到了,其实不用传递累计sum,可以在向下递归的时候改变参数sum😂,也不知道是不是受了非递归的启发。

当然,非递归方法不管是计算sum还是改变参数sum,总体思路还是一样的,需要用栈逐层回溯,没啥区别。

注意一个特殊样例:

[]
0

这使得终止递归的条件不能是root==NULL,而是root==叶子节点。 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(!root->left && !root->right){
            if(sum==root->val) return true;
            else return false;
        }
        sum -= (root->val);
        return (hasPathSum(root->left, sum) || hasPathSum(root->right, sum));
    }
    
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值