【陪伴式刷题】Day 13|二叉树| 102.二叉树的层序遍历(Binary Tree Level Order Traversal)

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

Input: root = 3,9,20,null,null,15,7 Output: \[3,9,20,15,7]

Example 2:

Input: root = 1 Output: \[1]

Example 3:

Input: root = \[\] Output: \[\]

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

英文版地址

leetcode.com/problems/bi...

中文版描述

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

输入: root = 3,9,20,null,null,15,7 输出: \[3,9,20,15,7]

示例 2:

输入: root = 1 输出: \[1]

示例 3:

输入: root = \[\] 输出: \[\]

提示:

  • 树中节点数目在范围 [0, 2000]
  • -1000 <= Node.val <= 1000

中文版地址

leetcode.cn/problems/bi...

解题方法

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<List<Integer>> result = new LinkedList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return result;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);
        int size = deque.size();
        List<Integer> line = new LinkedList<>();
        while (size-- > 0) {
            TreeNode treeNode = deque.pollFirst();
            TreeNode left = treeNode.left;
            if (left != null) {
                deque.addLast(left);
            }
            TreeNode right = treeNode.right;
            if (right != null) {
                deque.addLast(right);
            }
            line.add(treeNode.val);
            if (size == 0) {
                result.add(new LinkedList<>(line));
                line = new LinkedList<>();
                size = deque.size();
            }

        }
        return result;

    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点进一次队列出一次队列
  • 空间复杂度:O(n),其中 n 是二叉树中的节点个数,空间复杂度取决于队列开销,队列中的节点个数不会超过 n
相关推荐
小欣加油6 分钟前
leetcode169 多数元素
数据结构·c++·算法·leetcode·职场和发展
星马梦缘10 分钟前
数据库 第十三章 未完结版本
java·网络·数据库
程序猿乐锅11 分钟前
【JAVASE | 第十六篇】多线程
java·开发语言
做个文艺程序员12 分钟前
第01篇:Redis 从入门到上手:核心数据结构与 Java Spring Boot 实战详解
java·redis数据结构·redis入门·redis教程·java集成redis
影寂ldy15 分钟前
C# 多接口、同名冲突、显式实现、接口继承 完整笔记
java·笔记·c#
JAVA面经实录91716 分钟前
Spring Cloud Alibaba 微服务企业实战完整文档(架构+规范+调优+故障+源码)
java·运维·spring cloud·微服务
布局呆星17 分钟前
Spring Boot + JWT + Spring Security 认证授权实战:双角色、双 Token、方法级权限,一次讲透
java·开发语言
大G的笔记本17 分钟前
生产级 Spring Boot 网关完整实现方案
java·笔记·gateway
LucianaiB18 分钟前
Swarm管理面板的多项目配置策略与模型别名机制的效率分析
java·服务器·前端
qq_25183645723 分钟前
基于Spring Boot的数据标注与质检系统设计与实现
java·spring boot·后端