美文网首页
35_从上到下打印二叉树III

35_从上到下打印二叉树III

作者: 是新来的啊强呀 | 来源:发表于2020-05-27 11:00 被阅读0次

要求:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

思路:在上一题的基础上,创建一个flag表示奇偶位,偶数的时候将temp链表倒序,然后保存在res中。

    // 按之字形状顺序从上到下打印二叉树
    public ArrayList<ArrayList<Integer>> printFromTopToBottom3(TreeNode0 root){
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        Queue<TreeNode0> queue = new LinkedList<>();
        if(root!=null)queue.add(root);
        boolean flag = false;
        while(!queue.isEmpty()){
            ArrayList<Integer> temp = new ArrayList<>();
            // 队列中存储了多少个节点,都遍历出来
            for(int i=queue.size(); i>0; i--){
                TreeNode0 node = queue.poll();
                temp.add(node.value);
                if(node.left!=null)queue.add(node.left);
                if(node.right!=null)queue.add(node.right);
            }
            // 偶数位时,将temp倒序,在加入到res中
            if(flag){
                ArrayList<Integer> turn = new ArrayList<>();
                for(int i=temp.size()-1; i>=0; i--){
                    turn.add(temp.get(i));
                }
            }
            flag=!flag;
            res.add(temp);
        }
        return res;
    }

相关文章

网友评论

      本文标题:35_从上到下打印二叉树III

      本文链接:https://www.haomeiwen.com/subject/fcybahtx.html