2017.9.28
先用递归的办法找到所有的根节点到叶子节点的路径。
再一一计算和。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
public List<List<Integer>> pathToLeaf(TreeNode root){
List<List<Integer>> res = new LinkedList<>();
if(root == null){
return res;
}
if(root.left == null && root.right == null){
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(root.val);
res.add(tmp);
return res;
}
if(root.left != null){
List<List<Integer>> resLeft = pathToLeaf(root.left);
for(List<Integer> list: resLeft){
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(root.val);
tmp.addAll(list);
res.add(tmp);
}
}
if(root.right != null){
List<List<Integer>> resRight = pathToLeaf(root.right);
for(List<Integer> list: resRight){
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(root.val);
tmp.addAll(list);
res.add(tmp);
}
}
return res;
}
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// write your code here
List<List<Integer>> res = new LinkedList<>();
if(root == null){
return res;
}
List<List<Integer>> path = pathToLeaf(root);
for(List<Integer> list : path){
//System.out.println(list);
int sum = 0;
for(Integer num : list){
sum = sum + num;
}
if(sum == target){
res.add(list);
}
}
return res;
}
}