当前位置:网站首页>[LeetCode]剑指 Offer 32 - II. 从上到下打印二叉树 II
[LeetCode]剑指 Offer 32 - II. 从上到下打印二叉树 II
2022-08-02 15:41:00 【Spring-_-Bear】
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
题解:
/** * 剑指 Offer 32 - II. 从上到下打印二叉树 II * 树的广度优先遍历 */
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if (root != null) {
queue.add(root);
}
// 当队列不为空时遍历队列
while (!queue.isEmpty()) {
// 临时集合,存储当前层的遍历结果
List<Integer> tmp = new ArrayList<>();
// 遍历当前层的所有节点
for (int i = queue.size(); i > 0; i--) {
// 队列中的队首节点出队并加入 tmp 中
TreeNode node = queue.poll();
tmp.add(node.val);
// 将其左、右孩子加入到队列尾
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
res.add(tmp);
}
return res;
}
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
边栏推荐
猜你喜欢
随机推荐
Go-5-简单介绍fmt库
Eight big software attack overview of supply chain
【wpf】ListView 和 ItemsControl 的一点区别
智能座舱供应链的“新主角”
A tour of gRPC:06 - gRPC client straming 客户端流
数据中台应该怎样规划与建设?_光点科技
2.5 - 死锁
CefSharp practical demonstration
【[USACO12MAR]Cows in a Skyscraper G】【状压DP && DFS】
RecSys'22 推荐系统论文梳理
Qt reads Json files (including source code + comments)
JZ4 二维数组中的查找
QueryWrapper method explained
【[SCOI2005] 互不侵犯】【状压DP(含概念讲解)】
面试必问的HashCode技术内幕
20 Lectures on Disassembly of Multi-merchant Mall System Functions-Platform Distribution Overview
多商户商城系统功能拆解20讲-平台端分销概况
AI智能剪辑,仅需2秒一键提取精彩片段
DevOps开发工具对比
机械臂速成小指南(十八):圆弧规划