113. Path Sum II
来源:互联网 发布:php自学找工作 编辑:程序博客网 时间:2024/05/23 01:53
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]]
思路:就是回溯将每条路径都遍历一遍,将满足条件的记录下来
代码如下(已通过leetcode)
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if (root == null)
return lists;
List<Integer> list = new ArrayList<Integer>();
getpathofsum(lists, list, root, sum);
return lists;
}
private void getpathofsum(List<List<Integer>> lists, List<Integer> list, TreeNode root, int sum) {
// TODO Auto-generated method stub
if (root == null) {
return;
}
list.add(root.val);
if (root.left == null & root.right == null) {
if (sumoflist(list) == sum)
lists.add(new ArrayList<Integer>(list));
}
getpathofsum(lists, list, root.left, sum);
getpathofsum(lists, list, root.right, sum);
list.remove(list.size() - 1);
}
public int sumoflist(List<Integer> list) {
int sum = 0;
for (int k : list)
sum += k;
return sum;
}
}
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 注解
- 今日BBC-4/21
- 工业相机编程模型和流程
- ListView item监听左滑和右滑
- CocoaPods介绍与使用
- 113. Path Sum II
- c++作业四
- 第一次作业(5.安装linux)
- C++第4次实验—双色球问题
- 使用Axure制作App原型应该怎样设置尺寸?
- springmvc结合xheditor实现图文编辑
- tomcat网页发布
- 113.Power of Four
- ubuntu server设置时区和更新时间