Path Sum II

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]
]
C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10 
11 void pathSumHelper(TreeNode *root, int sum, vector<vector<int>>& result, vector<int>& current)
12 {
13     if(root==NULL)
14         return;
15     if((root->left==NULL)&&(root->right==NULL))
16     {
17         if(root->val==sum)
18         {
19             current.push_back(root->val);
20             result.push_back(current);
21             current.pop_back();
22         }
23     }
24     int remain=sumroot->val;
25     current.push_back(root->val);
26     pathSumHelper(root->left,remain,result,current);
27     pathSumHelper(root->right,remain,result,current);
28     current.pop_back();
29 }
30 class Solution {
31 public:
32     vector<vector<int> > pathSum(TreeNode *root, int sum) {
33         // Start typing your C/C++ solution below
34         // DO NOT write int main() function
35         vector<vector<int>> result;
36         vector<int> current;
37         pathSumHelper(root,sum,result,current);
38         return result;
39     }
40 };
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s