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;
}
}

0 0