leetcode-113 100%submissions

第一百一十三题:(很巧妙的二叉树递归)网上借鉴

1.边界情况:

根结点为空。

2.思路:

在递归途中依次加入结点值到数组path中,到达叶子结点时如果sum为0就加入这条路径path到ans自己中,当递归回到叶子结点的父节点把叶子结点从path中除去,依次类推得到结果(非常巧妙,我脑子笨时没想出来)。

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        // well the thing is to remeber the paths
        // use a string to remember the path? or vector? 
        // I will say use vector since you can push_back and pop_back
        // use the same recursive algo from the easy path sum and then pass one more parameter
        vector<vector<int>> ans;
        vector<int> path;
        if (root == NULL) return ans;
        recur(ans, root, sum, path);
        return ans;
    }
    
    void recur(vector<vector<int>>& ans, TreeNode* root, int sum, vector<int>& path) {
        
        if (root -> left == NULL && root->right == NULL & (sum - root->val) == 0) {
            path.push_back(root->val);
            ans.push_back(path);
            path.pop_back();
            return;
        }
        
        path.push_back(root->val);
        
        if (root->left) recur(ans, root->left, sum - root->val, path);
        if (root->right) recur(ans, root->right, sum - root->val, path);
        
        path.pop_back();
    }
    
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值