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

二叉树的层次遍历(BFS)

利用队列先进后出的特性

每层控制大小 进行遍历(list)

102. 二叉树的层序遍历

 

class Solution {List<List<Integer>> ans = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {checkfun01(root);return ans;}public void checkfun01(TreeNode node){if (node == null) return;Queue<TreeNode> que = new LinkedList<TreeNode>();que.offer(node);while(!que.isEmpty()){List<Integer> itemList = new  ArrayList<Integer>();int len =  que.size();while(len>0){len--;TreeNode model = que.poll(); if (model != null) { itemList.add(model.val);// 这里必须用 model,不能用 node!if (model.left != null) que.offer(model.left); if (model.right != null) que.offer(model.right); }}ans.add(itemList);}}
}

199. 二叉树的右视图

class Solution {List<Integer>  res = new ArrayList<Integer>();public List<Integer> rightSideView(TreeNode root) {chek01(root);return res;}public void chek01(TreeNode root){if(root == null) return;Queue<TreeNode> q = new LinkedList<TreeNode>();q.offer(root);while(!q.isEmpty()){int len = q.size(); List<Integer> item = new ArrayList<Integer>();for(int i = 0;i<len;i++){TreeNode tempNode = q.poll();if(tempNode != null){if(tempNode.left !=null ) q.offer(tempNode.left);if(tempNode.right != null) q.offer(tempNode.right);if(i==len-1) res.add(tempNode.val);}}}}
}

637. 二叉树的层平均值 

 

class Solution {List<Double> ans = new ArrayList<Double>();public List<Double> averageOfLevels(TreeNode root) {bfs(root);return ans;}public void bfs(TreeNode root){if(root == null) return;Queue<TreeNode> q = new LinkedList<TreeNode>();q.offer(root);while(!q.isEmpty()){int len = q.size();int n = len;Double sum = 0.0;for(int i  = 0;i<len;i++){TreeNode temp = q.poll();sum+=temp.val;if(temp.left !=null) q.offer(temp.left);if(temp.right!=null) q.offer(temp.right);}ans.add(sum/n);}}} 

 

http://www.dtcms.com/a/275074.html

相关文章:

  • ## SQLITE:多表(子母表)联合查询【DA_Project笔记】
  • 032_super关键字与父类访问
  • CSP-J/S 参赛选手注册报名流程
  • 如何应对风险和不确定性
  • 还在靠防火墙硬抗?网络安全需要从“单点防御“转向“系统化防护“!
  • AGV穿梭不“迷路”CCLinkIE转Modbus TCP的衔接技巧
  • 【AI大模型】超越RAG的搜索革命!分层框架让AI像专家团队一样深度思考
  • 三轴云台之三维重建算法篇
  • Microbiome:如何区分肠道中的有益菌?有害菌?
  • 嵌入式 数据结构学习 (六) 树、哈希表与内核链表
  • 【常见分布及其特征(2)】离散型随机变量-伯努利分布(0-1分布)
  • 滚珠导轨在发动机加工设备中起着什么作用?
  • Django老年健康问诊系统 计算机毕业设计源码32407
  • Windows11桌面解锁守护脚本
  • 05 唤醒词检测:让语音助手随时待命
  • 【跟着PMP学习项目管理】每日一练 - 3
  • 游戏gm系统
  • Kamailio 5.8.3与rtpengine双网卡SBC集成要点
  • TCP服务器与客户端三种方法实现
  • SHA-256算法流程分析与演示——github工程完善
  • 网络安全基础作业
  • 连锁门店如何统一固定资产盘点?总部+门店协同攻略
  • 佳能(Canon)摄像机存储卡提示格式化的恢复方法
  • 七月份了,考研数学该怎么复习?
  • AD736ARZ-R7精密真有效值转换器 高精度测量的首选方案
  • Telegraf vs. Logstash:实时数据处理架构中的关键组件对比
  • 网络编程(基本概念)
  • Maven下载与配置对Java项目的理解
  • TensorFlow2 study notes[1]
  • 9.卷积神经网络操作