二叉树中的和为某一值的路径

来源:互联网 发布:系统格式化数据恢复 编辑:程序博客网 时间:2024/05/21 18:50
public class Solution {        ArrayList<ArrayList<Integer>> arrayList=new ArrayList<ArrayList<Integer>>();      ArrayList<Integer> list=new ArrayList<Integer>();        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {        if(root == null) return arrayList;        list.add(root.val);        target-=root.val;//处理路径值的逻辑        if(target==0&&root.left==null&&root.right==null)            arrayList.add(new ArrayList<Integer>(list));//满足条件:加入        FindPath(root.left,target);//递归左子树        FindPath(root.right,target);        list.remove(list.size()-1);//回退条件(触发下一次的深度遍历)        return arrayList;//递归特点就在于其实它隐式的保存了递归过程的所有状态(隐式栈)    }}


这是看过的最简洁的了,不得不说,人外有人,吾辈仍需努力。

原创粉丝点击