题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
思路:
遍历所有叶子节点,判断路径之和是否为sum。用一维数组t存放临时答案,用二维数组ans存放最终答案。
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void f(TreeNode* root, int sum, vector<int> &t, vector<vector<int>> &ans){
if (root->left == nullptr && root->right == nullptr){
if (root->val == sum){
t.push_back(root->val);
ans.push_back(t);
t.pop_back();
}
}else if(root->left == nullptr){
t.push_back(root->val);
f(root->right, sum-root->val, t, ans);
t.pop_back();
}else if(root->right == nullptr){
t.push_back(root->val);
f(root->left, sum-root->val, t, ans);
t.pop_back();
}else{
t.push_back(root->val);
f(root->right, sum-root->val, t, ans);
f(root->left, sum-root->val, t, ans);
t.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
if (root == nullptr){
return ans;
}
vector<int> t;
f(root, sum, t, ans);
return ans;
}
};
discuss:
// 常规思路
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> paths;
vector<int> path;
findPaths(root, sum, path, paths);
return paths;
}
void findPaths(TreeNode *node, int sum, vector<int> &path, vector<vector<int>> &paths){
if (!node) return ;
path.push_back(node->val);
if (!node->left && !node->right && sum == node->val) paths.push_back(path);
findPaths(node->left, sum-node->val, path, paths);
findPaths(node->right, sum-node->val, path, paths);
path.pop_back();
}
};
本文探讨了在给定的二叉树中寻找所有从根节点到叶子节点的路径,这些路径上的节点值之和等于指定的目标和。通过递归算法,我们详细介绍了如何遍历树结构并收集符合条件的路径,同时提供了清晰的代码实现。
666

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



