剑指 Offer 32 - II. 从上到下打印二叉树 II + 层次遍历二叉树 + 按层存储
剑指 Offer 32 - II. 从上到下打印二叉树 II
Offer_32
题目描述:
题解分析:
- 这道题我一开始想到的解决方法较粗暴,就是使用两个变量来记录当前层的节点数和下一层的结点数。
- 以上的方法虽然可行,但是较复杂。实际每次队列里存储的就是当前层的所有结点,利用这个性质可以较快解题。
解法一:
package com.walegarrett.offer;
/**
* @Author WaleGarrett
* @Date 2021/2/1 14:50
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 题目:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
* 解析:使用队列按照层次打印层次遍历序列
*/
public class Offer_32_2 {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null)
return new ArrayList<List<Integer>>();
List<List<Integer>> list = new ArrayList<>();
Queue<TreeNode> que = new LinkedList<>();
que.add(root);
int currentLayerNum = 1;
int nextLayerNum = 0;
int cnt = 0;
List<Integer> current = new ArrayList<>();
while(!que.isEmpty()){
TreeNode temp = que.peek();
que.poll();
current.add(temp.val);
cnt++;
if(temp.left != null) {
que.offer(temp.left);
nextLayerNum++;
}
if(temp.right != null) {
que.offer(temp.right);
nextLayerNum++;
}
if(cnt == currentLayerNum){//当前层已经遍历结束
currentLayerNum = nextLayerNum;
nextLayerNum = 0;
cnt = 0;
list.add(current);
current = new ArrayList<>();//注意这里不能使用current.clear,否则所有的队列都将为空
}
}
return list;
}
}
解法二:
class Offer_32_2_1 {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null)
return new ArrayList<List<Integer>>();
List<List<Integer>> list = new ArrayList<>();
Queue<TreeNode> que = new LinkedList<>();
que.add(root);
while(!que.isEmpty()){
List<Integer> current = new ArrayList<>();
for(int i = que.size(); i> 0; i--){
TreeNode temp = que.peek();
que.poll();
current.add(temp.val);
if(temp.left != null) {
que.offer(temp.left);
}
if(temp.right != null) {
que.offer(temp.right);
}
}
list.add(current);
}
return list;
}
}
Either Excellent or Rusty
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了