Leetcode113 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_zhuo_/article/details/88105210
/**
 * 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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ans;//成功方案
        vector<int> temp;//当前方案
        //推出的条件
        DFS(root,ans,temp,sum,0);
        return ans;
    }
    //寻找可行路径:深度优先遍历
    //注意ans和temp都是引用!!!且pop_back()的位置考虑清楚
    void DFS(TreeNode* root,vector<vector<int>> &ans,vector<int> &temp,int sum,int cursum){
        if(root==NULL) return;//这里剪枝加了一个条件:root->val>(sum-cursum) 结果对于sum和val是负数的样例通不过
        cursum+=root->val;
        temp.push_back(root->val);
        if(cursum==sum&&isLeaf(root)){
            ans.push_back(temp);
            temp.pop_back();
            return;
        }//找到一条路径
        DFS(root->left,ans,temp,sum,cursum);
        DFS(root->right,ans,temp,sum,cursum);
        temp.pop_back();
        cursum-=root->val;
    }
    bool isLeaf(TreeNode *t)
    {
        return (t->left==NULL && t->right==NULL);
    }
};

猜你喜欢

转载自blog.csdn.net/Mr_zhuo_/article/details/88105210