leetcode Path Sum && Path Sum ||

路径总和问题解析
本文详细介绍了LeetCode中路径总和问题的两种解决方案,一种是判断是否存在满足特定和的路径,另一种是找出所有满足特定和的路径。通过递归算法实现了对二叉树的遍历,并记录了路径信息。

Path Sum

此题同 leetcode Sum Root to Leaf Numbers 解法,递归遍历时改变每个节点的值,该值为从起点到当前节点的路径和。

代码

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


Path Sum ||

Path Sum 大致相同,但要求输出所有路径和满足条件的路径,因此开辟空间保存路径信息即可。

代码

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > result;
        vector<int> onePath;
        if(root==NULL)
            return result;
        onePath.push_back(root->val);
        pathSumHelper(root, sum, onePath, result);
        return result;
    }
    
    void pathSumHelper(TreeNode *root, int sum, vector<int> onePath, vector<vector<int> > &result)
    {
        
        if(root==NULL)
            return ;
        
        if(!root->left&&!root->right&&root->val==sum)
        {
            result.push_back(onePath);
        }
        
        if(root->left)
        {
            onePath.push_back(root->left->val);
            root->left->val += root->val;
            pathSumHelper(root->left, sum, onePath, result);
            onePath.pop_back();
        }
        
        if(root->right)
        {
            onePath.push_back(root->right->val);
            root->right->val += root->val;
            pathSumHelper(root->right, sum, onePath, result);
            onePath.pop_back();
        }
        
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值