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]
]
Analysis:
Solutions:
C++:
A recursive solution: (16 ms)
void getPath(TreeNode *root, int sum, vector<vector<int> > &path, vector<int> &curPath)
{
if(root==NULL) return;
if(root->left==NULL && root->right==NULL && root->val==sum){
curPath.push_back(root->val);
path.push_back(curPath);
curPath.erase(curPath.end()-1, curPath.end());
}else{
curPath.push_back(root->val);
if(root->left!=NULL) getPath(root->left, sum-root->val, path, curPath);
if(root->right!=NULL) getPath(root->right, sum-root->val, path, curPath);
curPath.erase(curPath.end()-1, curPath.end());
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > path;
if(root==NULL) return path;
vector<int> curPath(1, root->val);
if(root->left==NULL && root->right==NULL && root->val==sum) path.push_back(curPath);
if(root->left!=NULL) getPath(root->left, sum-root->val, path, curPath);
if(root->right!=NULL) getPath(root->right, sum-root->val, path, curPath);
return path;
}
A non-recursive solution: (16 ms)
vector<vector<int>> pathSum(TreeNode* root, int sum)
{
vector<vector<int>> results;
if(root == NULL)
return results;
stack<TreeNode *> node_stack;
TreeNode *p_cur = root;
TreeNode *visited = NULL;
vector<int> result;
while(p_cur || !node_stack.empty()) {
if(p_cur) {
sum -= p_cur->val;
result.push_back(p_cur->val);
if(p_cur->left == NULL && p_cur->right == NULL && sum == 0) {
results.push_back(result);
}
node_stack.push(p_cur);
p_cur = p_cur->left;
} else {
p_cur = node_stack.top();
if(p_cur->right == NULL || p_cur->right == visited) {
sum += p_cur->val;
result.erase(result.end() - 1);
node_stack.pop();
visited = p_cur;
p_cur = NULL;
} else
p_cur = p_cur->right;
}
}
return results;
}