面试题32 - II. 从上到下打印二叉树 II

从上到下打印二叉树 II

题目描述

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。


示例:

提示:
节点总数 <= 1000

转载来源:力扣(LeetCode)


题目分析

这是一道很简单的层次遍历的题,但是我被它搞崩了心态[○・`Д´・ ○]
普通的层次遍历一开始只需要把当前节点放进队列,然后在队列不为空的条件下,把队列poll出来的节点的左右孩子分别add进去队里,如此执行直到队列为空;题目要求每一层都需要用一个list来存放,这问题也不大,记录下每一层的节点个数,然后依次读取这么多的节点就好;
那么问题来了,最搞我心态的就是是什么,就是ArrayDeque里的add方法和push方法

/**
     * Pushes an element onto the stack represented by this deque.  In other
     * words, inserts the element at the front of this deque.
     *
     * <p>This method is equivalent to {@link #addFirst}.
     *
     * @param e the element to push
     * @throws NullPointerException if the specified element is null
     */
    public void push(E e) {
        addFirst(e);
    }

 /**
     * Inserts the specified element at the end of this deque.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws NullPointerException if the specified element is null
     */
    public boolean add(E e) {
        addLast(e);
        return true;
    }

从源码可以看出,Deque的push方法是在双端队列的头部添加元素,而add方法是在双端队列的尾部添加元素,在很少用到双端队列的情况下,我没有意识到他们的区别,然后头铁的提交了几次都红了o(╥﹏╥)o


fun levelOrder(root: TreeNode?): List<List<Int>> {
        val list = ArrayList<ArrayList<Int>>()
        if(root == null)
            return list
        val queue =  ArrayDeque<TreeNode>()
        queue.add(root)
        while(!queue.isEmpty()){
            var size = queue.size
            val tmpList = ArrayList<Int>()
            while(size > 0){
                size--
                val tmpNode = queue.poll()
                tmpList.add(tmpNode.`val`)
                if(tmpNode.left != null)
                    queue.add(tmpNode.left)
                if(tmpNode.right != null)
                    queue.add(tmpNode.right)
            }
            list.add(tmpList)
        }
        return list
    }

代码文件


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容