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] ]
跟PathSumI一样
http://blog.csdn.net/kenden23/article/details/14223191
检查一颗二叉树是否有和某数相等的路径。和前面的最少深度二叉树思路差不多。
1 每进入一层,如果该层跟节点不为空,那么就加上这个值。
2 如果到了叶子节点,那么就与这个特定数比较,相等就说明存在这样的路径。
当然可以不是用递归优化一点算法吧。是用循环的话就可以在找到值的时候直接返回。递归也可以增加判断,找到的时候每层加判断迅速返回,不过感觉效果也高不了多少。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<int> onePath;
vector<vector<int> > path;
paSum(root, onePath, path, sum);
return path;
}
void paSum(TreeNode *node,vector<int> &onePath, vector<vector<int> > &path,
int overall, int levelNum = 0)
{
if(node == nullptr) return;
onePath.push_back(node->val);
levelNum += node->val;
paSum(node->left, onePath, path, overall, levelNum);
paSum(node->right, onePath, path, overall, levelNum);
if(node->left==nullptr && node->right==nullptr && overall==levelNum)
path.push_back(onePath);
onePath.pop_back();
}
};