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] ]
就是递归回溯法的应用。2到3星难度。
如下程序:
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<vector<int> > rs;
vector<int> tmp;
storeSums(rs, tmp, root, sum);
return rs;
}
void storeSums(vector<vector<int> > &rs, vector<int> &tmp, TreeNode *r, int sum)
{
if (!r) return;
tmp.push_back(r->val);
storeSums(rs, tmp, r->left, sum - r->val);
storeSums(rs, tmp, r->right, sum - r->val);
if (!r->left && !r->right && r->val == sum) rs.push_back(tmp);
tmp.pop_back();
}
下面这样写法可以说是很多递归回溯程序的标准形式了:
//2014-2-17 update
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<vector<int> > rs;
vector<int> tmp;
path(rs, tmp, root, sum);
return rs;
}
void path(vector<vector<int> > &rs, vector<int> &tmp, TreeNode *r, int sum)
{
if (!r) return;
if (!r->left && !r->right)
{
if (r->val == sum)
{
rs.push_back(tmp);
rs.back().push_back(sum);
}
return;
}
tmp.push_back(r->val);
path(rs, tmp, r->left, sum - r->val);
path(rs, tmp, r->right, sum - r->val);
tmp.pop_back();
}
本文详细介绍了使用递归回溯法解决二叉树中找到所有从根节点到叶子节点的路径,使得路径上的元素之和等于给定目标值的问题。通过给出具体的例子和代码实现,深入浅出地解释了该算法的核心思想和应用。
1197

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



