思路一:dfs+回溯剪枝
理解题意,要求路径起始为根节点,路径结尾为叶子节点,其它情况均不满足
public class Solution {
ArrayList<ArrayList<Integer>> list= new ArrayList<>();//总的路径
ArrayList<Integer> tempList = new ArrayList<>();//当前路径
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root==null)
return list;
tempList.add(root.val);//经过的节点先加进来
target -= root.val;//为了方便,采用倒减的方式,直至差为0
if(target<0)//没有必要再找下去了,提前返回
{
tempList.remove(tempList.size()-1);//节点不满足,往下找
return list;
}
if(target==0&&root.left==null&&root.right==null)//找到路径,加入总路径
list.add(new ArrayList<>(tempList));//防止引用传递
FindPath(root.left,target);
FindPath(root.right,target);
tempList.remove(tempList.size()-1);
return list;
}
}
时间O(N)每个节点遍历一次,空间递归栈,当二叉树退化链表,为O(N)
不算简单不算难,回溯和递归还得再练练
8-22 第二遍
没有bugfree
if(target==0&&root.left==null&&root.right==null)
{
list.add(new ArrayList<>(tempList));
tempList.remove(tempList.size()-1);
}
这里应该可以再加remove的操作,原理也是剪枝吧,满足要求了,就不需要再加,直接将最后一个数remove掉,进行下个节点判断