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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
跟PathSumI一样
http://blog.youkuaiyun.com/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();
}
};
本文介绍了一种算法,用于在给定的二叉树中查找所有从根到叶节点的路径,其中路径的数值总和等于指定的目标值。通过递归或循环方法实现,重点在于在达到叶子节点时比较路径总和是否与目标值相等。
183

被折叠的 条评论
为什么被折叠?



