一种特殊的树的遍历方式

普通层序遍历:

    //打印
    public List> levelOrder5(TreeNode root) {
        List> ret = new LinkedList<>();

        levelOrder5(root, 0, ret);
        return ret;
    }

    private void levelOrder5(TreeNode root, int level, List> ret) {
        if(root==null)
            return ;

        if(ret.size()==level){
            ret.add(new LinkedList<>());
        }

        ret.get(level).add(root.val);

        levelOrder5(root.left, level+1, ret);
        levelOrder5(root.right, level+1, ret);
    }

之字形层序遍历

    //之字形打印
    public List> levelOrder4(TreeNode root) {
        List> ret = new LinkedList<>();
        levelOrder4(root, 0, ret);
        return ret;
    }

    private void levelOrder4(TreeNode root, int level, List> ret) {
        if(root==null)
            return ;

        if(ret.size()==level){
            ret.add(new LinkedList<>());
        }

        if(level%2 == 0){
            ret.get(level).add(root.val);
        }else{
            ret.get(level).add(0, root.val);
        }

        levelOrder4(root.left, level+1, ret);
        levelOrder4(root.right, level+1, ret);
    }

你可能感兴趣的:(一种特殊的树的遍历方式)