Saturday, August 31, 2013

Path Sum - II (Print all Paths sum to target)

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]
]


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
void check(TreeNode *root, vector<int> v, vector<vector<int> > &result, int current_sum, int target_sum)
{
    if(!root)
        return;
    
    current_sum += root->val;
    v.push_back(root->val);
    if(!root->left && !root->right)
    {
        if(current_sum == target_sum)
        result.push_back(v);
        return ;
    }
    
    
    check(root->left, v, result,  current_sum, target_sum) ;
    check(root->right, v, result, current_sum, target_sum);
                
 }

vector<vector<int> > pathSum(TreeNode *root, int sum) {
    vector<int> v;
    vector<vector<int> > vr;
    check(root, v, vr, 0, sum);
    return vr;
}
};

No comments:

Post a Comment