Path Sum II
来源:互联网 发布:中国人名大学网络教育 编辑:程序博客网 时间:2024/05/16 10:46
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 1return
[ [5,4,11,2], [5,8,4,5]]这是一个典型的深度搜索的例子。
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { ArrayList<List<Integer>> result=new ArrayList<List<Integer>>();if(root==null)return result;ArrayList<Integer> value=new ArrayList<Integer>();value.add(root.val);dfs(root,sum-root.val,value,result);return result;}private List<List<Integer>> dfs(TreeNode root,int sum,List<Integer> value,List<List<Integer>> result){if(root.left==null&&root.right==null&&sum==0){List<Integer> l=new ArrayList<Integer>(value);result.add(l);}if(root.left!=null){value.add(root.left.val);dfs(root.left,sum-root.left.val,value,result);value.remove(value.size()-1);}if(root.right!=null){value.add(root.right.val);dfs(root.right,sum-root.right.val,value,result);value.remove(value.size()-1);}return result;}}
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- Js学习第三天----字符集
- 编译报错解决。
- springMvc 将对象json返回时自动忽略掉对象中的特定属性的注解方式
- python正则表达式
- HDU 1873 看病要排队
- Path Sum II
- UIScrollView和UIPageControl
- java 中的观察者模式
- uva 1103 dfs
- 啊哈,算法!-----dfs3
- 别误用IsDigit与IsNumber函数
- OpenCV中计算二值图像的重心
- Maven(一)简介和基本安装使用
- Android中ViewPager+Fragment的基本使用