题目:
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] ]
/**
* 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<vector<int>> ans;
vector<int> i_vec;
dfs(root, ans, i_vec, 0, sum);
return ans;
}
void dfs(TreeNode *root, vector<vector<int>> &i_vec_vec, vector<int> i_vec, int cur, int sum) {
if(root == NULL)
return;
cur += root->val;
i_vec.push_back(root->val);
if(root->left == NULL && root->right == NULL && cur == sum)
i_vec_vec.push_back(i_vec);
dfs(root->left, i_vec_vec, i_vec, cur, sum);
dfs(root->right, i_vec_vec, i_vec, cur, sum);
}
};
本文介绍了一种算法,用于在给定的二叉树中找到所有从根节点到叶子节点的路径,使得这些路径上的元素之和等于指定的数值。通过深度优先搜索(DFS)的方法,我们可以有效地解决这个问题。
1199

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



