首页 > 代码库 > LeetCode[Tree]: Path Sum II
LeetCode[Tree]: Path Sum II
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,
return
这个题目适合用递归来解,我的C++代码实现如下:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > paths;
vector<int> curr_path;
if (!root) return paths;
find(root, sum, paths, curr_path);
return paths;
}
private:
void find(TreeNode *root, int sum, vector<vector<int> > &paths, vector<int> &curr_path) {
curr_path.push_back(root->val);
if (root->left == nullptr && root->right == nullptr)
if (root->val == sum) paths.push_back(curr_path);
if (root->left) {
find(root->left, sum - root->val, paths, curr_path);
curr_path.pop_back();
}
if (root->right) {
find(root->right, sum - root->val, paths, curr_path);
curr_path.pop_back();
}
}
};
时间性能如下图所示:
LeetCode[Tree]: Path Sum II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。