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 andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
package leetcode;
import java.util.ArrayList;
public class Path_sum_ii {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(0);
TreeNode t2 = new TreeNode(1);
TreeNode t3 = new TreeNode(1);
t1.right = t2;
t1.left = t3;
System.out.println(pathSum(t1, 1));
}
static ArrayList<ArrayList<Integer>> Al = new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> al = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
if(root == null) { //如果节点为空,则直接返回
return Al;
}else {
al.add(root.val); //否则把相应的数值添加到相应的数组之后
sum =sum-root.val; //对和值进行重新处理
}
if(sum == 0 && root.left == null && root.right == null) { //当找到满足条件的叶子节点
ArrayList<Integer> temp = new ArrayList<>(al); //新建一个数组,将满足条件的数组复制过去
al.remove(al.size()-1); //把al原数组最后一个元素去掉,便于接下来的寻找和添加
Al.add(temp); //把符合条件的赋值数组,添加起来作为一个正确答案
}else {
pathSum(root.left, sum); //如果不满条件就接着查找左子树和右子树
pathSum(root.right, sum);
al.remove(al.size()-1); //这个是理解的重点,我原来没有加这个语句说我算法复杂度过大,运行时间超出了
//其实,每个叶子节点也是有左节点和右节点,只不过都是空节点,如果找到了符合条件的叶子节点,会把最后一个元素删除掉,这个叶子节点不符合当遍历其左子节点和右子节点
//之后也会把最后一个元素删除掉.当一个节点的左不为空右也不为空,不管其左和右的情况如何,最后把最后一个元素删除掉,便于递归回去上一层次的返回.
//这是一个重点,重点,重点,没有这个无法完成算法.
}
return Al;
}
}