牛客(24)二叉树中和为某一值的路径

//    题目描述
//    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
//    路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }

    }

    public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        if (root==null){
            return arrayLists;
        }
        int sum=0;
        //传递引用
        FindPath(arrayLists,arrayList,root,target,sum);
        return arrayLists;
    }
    public static void FindPath(ArrayList<ArrayList<Integer>> arrayLists,ArrayList<Integer> arrayList,TreeNode root, int target,int sum) {
        if (root==null){
            return;
        }
        sum += root.val;
        arrayList.add(root.val);//节点添加到动态arrayList
        if (root.right==null&&root.left==null){//判断叶子节点
            if (sum==target){//判断计算结果
                //创建新对象加入arrayLists
                arrayLists.add(new ArrayList<Integer>(arrayList));
            }
            //返回上一层删除本层的节点
            arrayList.remove(arrayList.size()-1);
            return;
        }
        //进入下一层
        FindPath(arrayLists,arrayList,root.left,target,sum);
        FindPath(arrayLists,arrayList,root.right,target,sum);
        //返回上一层删除本层的节点
        arrayList.remove(arrayList.size()-1);
    }

 

posted @ 2018-05-09 15:47  楷兵  阅读(121)  评论(0编辑  收藏  举报