LeetCode OJ:Path Sum II(路径和II)
2024-10-21 06:11:50
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,代码如下:
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> res;
dfs(root, res, sum);
return ret;
} void dfs(TreeNode * root, vector<int> res, int left)
{
if(!root) return;
if(!root->left && !root->right && left == root->val){
res.push_back(root->val);
ret.push_back(res);
}
if(left <= root->val)
return;
else{
res.push_back(root->val);
if(root->left)
dfs(root->left, res, left -= root->val);
if(root->right)
dfs(root->right, res, left -= root->val);
}
}
private:
vector<vector<int>> ret;
};
java版本代码如下,方法相同,就是java的引用处理起来稍微麻烦点,递归尾部应该pop一下。
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
Stack<Integer> tmp = new Stack<Integer>();
dfs(ret, tmp, root, sum);
return ret;
} public void dfs(List<List<Integer>> ret, Stack<Integer> tmp, TreeNode root, int remain){
if(root == null) return;
tmp.push(root.val);
if(root.left == null && root.right == null)
if(remain == root.val)
ret.add((Stack<Integer>)tmp.clone());
if(root.left != null) dfs(ret, tmp, root.left, remain - root.val);
if(root.right != null) dfs(ret, tmp, root.right, remain - root.val);
tmp.pop();
}
}
最新文章
- CALayer的transform属性
- 欧拉回路(hdu3018)
- ListView实现Item局部刷新
- leetcode-Single Number III 找独数
- opencv笔记4:模板运算和常见滤波操作
- log4Net 简单配置实用
- Nginx - Additional Modules, About Your Visitors
- Android Game
- [转]MVC模式已死?何不试试MOVE
- 使用ActionBar实现Tab导航(快速生成Tab样式)
- Mac下MAMP初试体验
- 笔试题&;amp;面试题:CW输出矩阵
- Unity进阶----AssetBundle_03(2018/11/07)
- centos官网下载地址
- C语言数组一种巧妙的使用方式
- PCL点云配准(3)
- 转发-基于ASP.NET MVC 4/5 Razor的模块化/插件式架构实现
- 2017-5-19&;5-23/系统性能指标
- yii2 HTML组手
- Kafka集群副本分配算法解析