遍历二叉树所有路径并求指定值

来源:互联网 发布:linux rhel 环境变量 编辑:程序博客网 时间:2024/06/12 00:44

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

public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}public class Solution {    public static ArrayList<Integer> change(ArrayList<TreeNode> al){        ArrayList<Integer> res = new ArrayList<Integer>();        for(TreeNode t : al){            res.add(t.val);        }        return res;    }    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();//保存最终所有路径    ArrayList<TreeNode> onePath = new ArrayList<TreeNode>();//保存当前遍历路径的集合    int max = 0;//保存路径权值    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {        if(root == null) return result;        max += root.val;        onePath.add(root);        if(root.left == null && root.right == null){            if(target == max){                result.add(change(onePath));                }            //return result;        }        if(root.left != null){            FindPath(root.left, target);        }        if(root.right != null){            FindPath(root.right, target);        }        onePath.remove(root);        max -= root.val;        return result;    }}
0 0
原创粉丝点击