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] ]
思路:此题与 Path Sum类似,只不过需要将路径上的点都输出来。如何做到?
添加一个辅助的向量v,用来记录到达第i层,第p个结点时,从根结点到p的父结点时路径上的所有结点。因此,当到达叶子结点时,这个辅助向量v就已经记录了到达该叶子结点前的所有结点。如果到达此叶子结点的路径符合要求,就将该叶子结点也放入辅助向量中,并将此辅助向量添加到最终的二维向量vv中。
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<int> v;
if(!root)
return vv;
else
{
path(root,0,sum,v);
}
return vv;
}
void path(TreeNode* root, int total, int sum, vector<int> v)
{
//toatl : 到目前结点root之前的路径上的所有元素和
v.push_back(root->val);//push当前结点的值
if(!root->left && !root->right)
{
if(total+root->val == sum)
vv.push_back(v);
}
else if(root->left && !root->right)
{
path(root->left,total+root->val,sum,v);
}
else if(root->right && !root->left)
{
path(root->right,total+root->val,sum,v);
}
else
{
path(root->left,total+root->val,sum,v);
path(root->right,total+root->val,sum,v);
}
}
private:
vector<vector<int> > vv;
};
本文介绍了一种算法,用于查找二叉树中所有从根节点到叶节点的路径,其中路径上节点值的总和等于给定的数值。通过递归方式实现,使用辅助向量记录路径。
312

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



