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

来源:互联网 发布:android编程实战 pdf 编辑:程序博客网 时间:2024/05/23 20:05

题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {        ArrayList<ArrayList<Integer>> allPaths = new ArrayList<ArrayList<Integer>>();        ArrayList<Integer> path = new ArrayList<Integer>();        getPath(root, target, path, allPaths);        return allPaths;    }    public void getPath(TreeNode root, int target, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> allPaths){        if(root == null){            return;        }        path.add(root.val);        if(root.left == null && root.right == null && target == root.val){            allPaths.add((ArrayList<Integer>) path.clone());            path.remove(path.size() - 1);        }        else{            if(root.left != null){                getPath(root.left, target - root.val, path, allPaths);            }            if(root.right != null){                getPath(root.right, target - root.val, path, allPaths);            }            path.remove(path.size() - 1);        }    }
0 0