Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/43c09902af45a4eac9e7 to your computer and use it in GitHub Desktop.
Save xiren-wang/43c09902af45a4eac9e7 to your computer and use it in GitHub Desktop.
path sum II.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
* 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]
]
*/
class Solution {
public:
//recursive find path (root->left/right, sum - root.val)
// if sum == 0, and !root->left && !root->right, a path is found
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > vvInt;
if (!root)
return vvInt;
vector<int> vPath;
findPathVector(root, vPath, vvInt, sum);
return vvInt;
}
void findPathVector(TreeNode *root, vector<int> path, vector<vector<int> > &vvInt, int sum) {
if (!root)
return;
int newSum = sum - root->val;
path.push_back(root->val);
if(!root->right && !root->left) {
if (newSum == 0 ) //found a root-leaf path
vvInt.push_back(path);
return;
}
if (root->left)
findPathVector(root->left, path, vvInt, newSum);
if (root->right)
findPathVector(root->right, path, vvInt, newSum);
return;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment