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] ]
题目解析:
方案一:
输出所有可能的路径和等于sum的情况。方法类似上题,只有叶节点且路径和等于sum时才将tmp放入res中。递归的时候,传递vector<int>的副本比较好,不用操心入栈出栈的问题。
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
if(root == NULL)
return res;
vector<int> tmp;
GenerateSum(root,sum,tmp);
return res;
}
void GenerateSum(TreeNode *root,int sum,vector<int> tmp){
if(root == NULL)
return;
if(root->val == sum && root->left == NULL && root->right == NULL){
tmp.push_back(root->val);
res.push_back(tmp);
return;
}
tmp.push_back(root->val);
GenerateSum(root->left,sum-root->val,tmp);
GenerateSum(root->right,sum-root->val,tmp);
}
private:
vector<vector<int> >res;
};
方案二:
之前写过的程序:面试题25:二叉树中和为某一值的路径。但是用的是栈实现的,每次要考虑好什么时候入栈,什么时候出栈。并且当时也没考虑是否到达叶节点。