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

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

题目

链接

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

问题描述

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

示例

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

3  

/
9 20
/
15 7
返回:

[3,9,20,15,7]

提示

节点总数 <= 1000

思路

用队列来存放数据,每个结点先入列,然后处理到该节点时,存放val,将左右节点放入。

复杂度分析

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

代码

Java

public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<Integer> ans = new ArrayList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            ans.add(tmp.val);
            if (tmp.left != null) {
                queue.add(tmp.left);
            }
            if (tmp.right != null) {
                queue.add(tmp.right);
            }
        }
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            res[i] = ans.get(i);
        }
        return res;
    }
posted @ 2022-03-19 19:25  cheng102e  阅读(30)  评论(0)    收藏  举报