Wednesday, October 8, 2014

Path Sum II

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

        pathSum(root->left,sum-root->val,ret,path);
        pathSum(root->right,sum-root->val,ret,path);
        path.pop_back();
    }

};

No comments:

Post a Comment