当前位置: 首页 > news >正文

队列--二叉树层序遍历

/*1/ \2   3/\   /\4  5 6  7利用LinkedListQueue1. 头 [1] 尾12.头 [2 3] 尾1 23.头 [3 4 5] 尾1 24.头 [4 5 6 7] 尾1 2 35.头 [] 尾1 2 3 4 5 6 7*/

代码:

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result = new ArrayList<>();if(root == null) {return result;}LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();queue.offer(root);int c1 = 1;		// 本层节点个数while (!queue.isEmpty()) {int c2 = 0; 	// 下层节点个数List<Integer> level = new ArrayList<>();for (int i = 0; i < c1; i++) {TreeNode node = queue.poll();level.add(node.val);if (node.left != null) {queue.offer(node.left);c2++;}if (node.right != null) {queue.offer(node.right);c2++;}}c1 = c2;result.add(level);}return result;}// 自定义队列static class LinkedListQueue<E> {private static class Node<E> {E value;Node<E> next;public Node(E value, Node<E> next) {this.value = value;this.next = next;}}private final Node<E> head = new Node<>(null, null);private Node<E> tail = head;int size = 0;private int capacity = Integer.MAX_VALUE;{tail.next = head;}public LinkedListQueue() {}public LinkedListQueue(int capacity) {this.capacity = capacity;}public boolean offer(E value) {if (isFull()) {return false;}Node<E> added = new Node<>(value, head);tail.next = added;tail = added;size++;return true;}public E poll() {if (isEmpty()) {return null;}Node<E> first = head.next;head.next = first.next;if (first == tail) {tail = head;}size--;return first.value;}public E peek() {if (isEmpty()) {return null;}return head.next.value;}public boolean isEmpty() {return head == tail;}public boolean isFull() {return size == capacity;}}
}

http://www.lryc.cn/news/185008.html

相关文章:

  • Ceph入门到精通-Linux内核网络参数优化小结
  • AWK语言第二版 2.6个人库 2.7小结
  • 8年经验之谈 —— Web ui自动化测试框架总结!
  • Kafka在企业级应用中的实践
  • 使用企业订货系统后的效果|软件定制开发|APP小程序搭建
  • STL关联式容器set,multiset,pair,map
  • MFC文本输出学习
  • Python 数据分析与挖掘(一)
  • 【问题证明】矩阵方程化为特征值方程求得的特征值为什么是全部特征值?不会丢解吗?
  • 虹科干货 | 不是吧,Redis Enterprise也能当向量数据库来用?
  • 汽车驾驶 - 四梁六柱是什么
  • CI522 13.56MHZ电动车NFC测试资料
  • 【微信小程序开发】一文学会使用CSS样式布局与美化
  • 漏刻有时物联网环境态势感知大数据(设备列表、动态折线图)
  • 【力扣】单调栈:901. 股票价格跨度
  • 4_使用预训练模型 微调训练CIFAR10
  • 机器学习笔记(一)
  • 学习在原地打转的原因与解决 如何步步为营 一日千里快速进步 考研工程计算 1万小时=416.666666667 天
  • 194、SpringBoot --- 下载和安装 Erlang 、 RabbitMQ
  • 机器学习7:pytorch的逻辑回归
  • Java应用程序中如何实现FTP功能 | 代码示例和教程
  • kotlin:list的for循环
  • asp.net电影院选座系统VS开发sqlserver数据库web结构c#编程Microsoft Visual Studio
  • CSS鼠标指针表
  • 树的基本概念及二叉树
  • BUUCTF Basic 解题记录--BUU XXE COURSE
  • kotlin:LogKit
  • yolo_tracking中osnet不支持.pth格式,而model_zoo中仅有.pth
  • Tailwind CSS浅析与实操
  • Activiti工作流引擎详解与应用