您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:树: Path SumII(113)

2016-08-25 16:48 316 查看
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]
]


算法

dfs

O(n)

class Solution {
private:
void dfs(TreeNode *root, int rest, vector<int> &path,
vector<vector<int> > &res) {
if (root == NULL)
return;
path.push_back(root->val);
rest -= root->val;
if (root->left == NULL && root->right == NULL) {
if (rest == 0)
res.push_back(path);
} else {
if (root->left)
dfs(root->left, rest, path, res);
if (root->right)
dfs(root->right, rest, path, res);
}
path.pop_back();
}
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > res;
vector<int> path;
dfs(root, sum, path, res);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: