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> > res;
vector<int> cur;
dfs(root, sum, cur, res);
return res;
}
void dfs(TreeNode *root, int gap, vector<int> &cur, vector<vector<int> > &res) {
if (!root) {
return ;
}
cur.push_back(root->val);
if (!root->left && !root->right) {
if (gap == root->val) {
res.push_back(cur);
}
}
dfs(root->left, gap - root->val, cur, res);
dfs(root->right, gap - root->val, cur, res);
cur.pop_back();
}
};
本文介绍了一种算法,该算法接收一个二叉树及一个目标和作为输入,然后找出所有从根节点到叶子节点的路径,这些路径上的节点值之和等于给定的目标和。例如,在给定的二叉树中寻找和为22的路径。
3391

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



