【LeetCode】LeetCode 112.路径总和

LeetCode 112.路径总和

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

题目

image-20220718221106312

image-20220718221116458

解答

递归法

count开始做减法而不是从0开始做加法

class Solution {
public:
    bool traversal(TreeNode* cur, int count){
        //到叶子节点且count为0,即找到了一条路径
        if(!cur->left && !cur->right && count == 0){
            return true;
        }
        //到叶子节点但是count不为0
        if(!cur->left && !cur->right){
            return false;
        }

        if(cur->left){
            count -= cur->left->val;
            if(traversal(cur->left,count))  return true;
            count += cur->left->val;//回溯
        }

        if(cur->right){
            count -= cur->right->val;
            if(traversal(cur->right,count))  return true;
            count += cur->right->val;//回溯
        }

        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == NULL)    return false;
        return traversal(root,targetSum - root->val);
    }
};

迭代法

使用栈模拟递归。

此时栈内的一个元素不仅要记录该节点的指针,还要记录从头节点到该节点的路径数值的总和。

将栈内的一个元素定义为pair<Treenode*,int>pair<节点指针,路径数值>

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == NULL)    return false;
        stack<pair<TreeNode*, int>> st;
        st.push(pair<TreeNode*, int>(root, root->val));
        while(!st.empty()){
            pair<TreeNode*, int> node = st.top();
            st.pop();

            if(!node.first->left &&  !node.first->right && targetSum == node.second){
                return true;
            }

            if(node.first->left){
                st.push(pair<TreeNode*, int>(node.first->left,node.second + node.first->left->val));
            }

            if(node.first->right){
                st.push(pair<TreeNode*, int>(node.first->right,node.second + node.first->right->val));
            }
        }
        return false;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NUAA_Peter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值