Thursday, April 18, 2013

Leetcode: Path Sum II in C++


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]
]
Solution:
void pathSumHelp(TreeNode *root, int sum, vector<int> cur,vector<vector<int> >& result )
    {
        if(sum-root->val==0&&!root->left&&!root->right)
        {
            cur.push_back(root->val);
            result.push_back(cur);
            return;
        }
        cur.push_back(root->val);
        if(root->left)
        {
            pathSumHelp(root->left,sum-root->val,cur,result);
        }
        if(root->right)
        {
            pathSumHelp(root->right,sum-root->val,cur,result);
        }
    }
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > result;
        if(!root)
            return result;
        vector<int> cur;
        pathSumHelp(root,sum,cur,result);
        return result;
    }

No comments:

Post a Comment