Leetcode:Path Sum II
来源:互联网 发布:linux命令日志文件 编辑:程序博客网 时间:2024/06/07 14:44
url:
https://leetcode.com/problems/path-sum-ii/description/
描述:
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]
]
解题思路:
深度优先搜索
示例代码:
class Solution { private List<List<Integer>> res = new ArrayList(); public List<List<Integer>> pathSum(TreeNode root, int sum) { dfs(sum,root,new ArrayList<Integer>()); return res; } private void dfs(int sum,TreeNode root,List<Integer> temp){ if(root==null) return; if(sum-root.val==0&&root.left==null&&root.right==null){ temp.add(root.val); res.add(new ArrayList(temp)); }else if(sum>0||root!=null){ temp.add(root.val); dfs(sum-root.val,root.left,temp); dfs(sum-root.val,root.right,temp); } temp.remove(temp.size()-1); }}
阅读全文
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- golang语言乱谈之Interface
- mysql 实现秒杀
- 自定义标题栏组合控件
- MVC设计模式
- JSONP原理--解决ajax跨域问题
- Leetcode:Path Sum II
- Android Studio【通用&方便】插件方式打包jar(不包含资源文件)
- 数据仓库
- 网络连接+HttpClient+AsyncTask
- UVALive 6085|Chemistry|字符串处理
- 【BZOJ 3591】 最长上升子序列
- LCA总结
- ROS常用命令
- MVP+Rxjava请求数据