Path Sum II

来源:互联网 发布:mysql高并发写入方案 编辑:程序博客网 时间:2024/05/19 04:29
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {        // Start typing your Java solution below        // DO NOT write main() function        if(root == null) return new ArrayList<ArrayList<Integer>>();        return path(root, sum - root.val);    }        public ArrayList<ArrayList<Integer>> path(TreeNode root, int sum) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        if(root.left == null && root.right == null) {            ArrayList<Integer> sub = new ArrayList<Integer>();            if(sum == 0) {                sub.add(root.val);                result.add(sub);            }        }else {            if(root.left != null) {                for(ArrayList<Integer> sub : path(root.left, sum - root.left.val)) {                    sub.add(0, root.val);                    result.add(sub);                }            }            if(root.right != null) {                for(ArrayList<Integer> sub : path(root.right, sum - root.right.val)) {                    sub.add(0, root.val);                    result.add(sub);                }            }        }        return result;    }


原创粉丝点击