113.PathSumII

你快乐吗?

Posted by bbkgl on September 26, 2019

113. Path Sum II


C++。dfs,回溯,不剪枝。没有说是正整数就不要剪枝了。。。

typedef TreeNode* TNP;

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ans;
        if (!root) return ans;
        vector<int> tpath;
        tpath.push_back(root->val);
        dfs(root, tpath, ans, root->val, sum);
        tpath.pop_back();
        return ans;
    }
    
    void dfs(TNP root, vector<int> &tpath, vector<vector<int>> &ans, int tsum, int &sum) {
        if (root->left) {
            tpath.push_back(root->left->val);
            dfs(root->left, tpath, ans, tsum + root->left->val, sum);
            tpath.pop_back();
        }
        if(root->right) {
            tpath.push_back(root->right->val);
            dfs(root->right, tpath, ans, tsum + root->right->val, sum);
            tpath.pop_back();
        }
        if (!root->left && !root->right) {
            if (tsum == sum) ans.push_back(tpath);
        }
    }
};