问题:
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] ]分析:
有点像permutation那道题。
代码:
class Solution {
public:
void pathSum(vector<vector<int> > &result, vector<int> temp, TreeNode *root, int sum) {
if (!root) return;
if (root->val == sum && !root->left && !root->right) {
temp.push_back(root->val);
result.push_back(temp);
return;
}
else {
temp.push_back(root->val);
pathSum(result, temp, root->left, sum - root->val);
pathSum(result, temp, root->right, sum - root->val);
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> temp;
pathSum(result, temp, root, sum);
return result;
}
};

本文探讨了一道经典的二叉树遍历问题——寻找所有从根节点到叶子节点的路径,使得路径上的节点值之和等于给定的总和。通过递归的方法实现了这一目标,并提供了详细的代码实现。
1201

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



