Monday, November 25, 2013

LeetCode Problem : Path Sum II

Problem


Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]

Code


bool ps(TreeNode *root, int sum, vector<int>& tmp,vector<vector<int> >& result,int pos) {
    if(!root)
        return false;
    if(tmp.size() == pos){
        tmp.resize(2*tmp.size() + 1);
    }
    tmp[pos] = root->val;
    if(!root->left && !root->right &&
    sum == root->val){ 
        vector<int> temp(pos + 1);
        for(int i = 0;i <= pos; ++i){
            temp[i] = tmp[i];
        }
        result.push_back(temp);
        return true;
    }
    bool ret1 = ps(root->left,sum - root->val,tmp,result,pos + 1);
    bool ret2 = ps(root->right,sum - root->val,tmp,result,pos + 1);
    return ret1 || ret2;
}

vector<vector<int> > pathSum(TreeNode *root, int sum) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    vector<vector<int> > result;
    if(!root)
        return result;

    vector<int> tmp;
    ps(root,sum,tmp,result,0);
    return result;
}

No comments:

Post a Comment