剑指 Offer 32 - II. 从上到下打印二叉树 II

剑指 Offer 32 - II. 从上到下打印二叉树 II

题目

链接

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/

问题描述

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

节点总数 <= 1000

示例

例如:
给定二叉树: [3,9,20,null,null,15,7],

3  

/
9 20
/
15 7
返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]

提示

思路

打印的时候多一个考虑方式,对于具体某个节点的时候,把当前行处理完毕。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.add(root);
        }

        while (!queue.isEmpty()) {
            List<Integer> ans = new ArrayList<>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode tmp = queue.poll();
                ans.add(tmp.val);
                if (tmp.left != null) {
                    queue.add(tmp.left);
                }
                if (tmp.right != null) {
                    queue.add(tmp.right);
                }
            }
            res.add(ans);
        }
        return res;
    }
posted @ 2022-03-19 21:56  cheng102e  阅读(28)  评论(0)    收藏  举报