力扣爆刷第141天之二叉树十连刷(层序遍历)

力扣爆刷第141天之二叉树十连刷(层序遍历)

文章目录

      • 力扣爆刷第141天之二叉树十连刷(层序遍历)
      • 一、102. 二叉树的层序遍历
      • 二、107. 二叉树的层序遍历 II
      • 三、199. 二叉树的右视图
      • 四、637. 二叉树的层平均值
      • 五、429. N 叉树的层序遍历
      • 六、515. 在每个树行中找最大值
      • 七、116. 填充每个节点的下一个右侧节点指针
      • 八、117. 填充每个节点的下一个右侧节点指针 II
      • 九、104. 二叉树的最大深度
      • 十、111. 二叉树的最小深度

一、102. 二叉树的层序遍历

题目链接:https://leetcode.cn/problems/binary-tree-level-order-traversal/description/
思路:层序遍历,使用队列完成,经典题目。通过队列size来控制层序遍历。

class Solution {List<List<Integer>> result = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {if(root == null) return result;LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();List<Integer> list = new ArrayList<>();for(int i = 0; i < size; i++) {TreeNode node = queue.poll();list.add(node.val);if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}result.add(list);}return result;}
}

二、107. 二叉树的层序遍历 II

题目链接:https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/description/
思路:要求从叶子层到根节点层进行层序遍历,直接层序遍历,然后翻转数组。

class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> result = new ArrayList<>();LinkedList<TreeNode> queue = new LinkedList<>();if(root == null) return result;queue.add(root);while(!queue.isEmpty()) {int size = queue.size();List<Integer> list = new ArrayList<>();for(int i = 0; i < size; i++) {TreeNode node = queue.poll();list.add(node.val);if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}result.add(list);}int i = 0, j = result.size()-1;while(i < j) {List<Integer> t = result.get(i);result.set(i, result.get(j));result.set(j, t);i++;j--;}return result;}
}

三、199. 二叉树的右视图

题目链接:https://leetcode.cn/problems/binary-tree-right-side-view/description/
思路:本题可以直接层序遍历,只需要在每一层遍历到size时记录数据。也可以直接前序遍历,只不过遍历的顺序是右中左,而且维护一个深度值,只有每次突破深度时才记录。

class Solution {List<Integer> list = new ArrayList<>();public List<Integer> rightSideView(TreeNode root) {if(root == null) return list;LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();for(int i = 0; i < size; i++) {TreeNode node = queue.poll();if(i == size-1) {list.add(node.val);}if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}}return list;}}

四、637. 二叉树的层平均值

题目链接:https://leetcode.cn/problems/average-of-levels-in-binary-tree/description/
思路:直接层序遍历,然后收集每一层的总和,利用size算平均值。

class Solution {public List<Double> averageOfLevels(TreeNode root) {List<Double> list = new ArrayList<>();LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();double avg = 0;for(int i = 0; i < size; i++) {TreeNode node = queue.poll();avg += node.val;if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}list.add(avg/size);}return list;}
}

五、429. N 叉树的层序遍历

题目链接:https://leetcode.cn/problems/n-ary-tree-level-order-traversal/description/
思路:N叉树的层序遍历,比二叉树来说,只是多了几个叉,不需要在直接写左右子树了,直接一个for循环,把子节点全遍历出来。

/*
// Definition for a Node.
class Node {public int val;public List<Node> children;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, List<Node> _children) {val = _val;children = _children;}
};
*/class Solution {public List<List<Integer>> levelOrder(Node root) {List<List<Integer>> result = new ArrayList<>();if(root == null) return result;LinkedList<Node> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();List<Integer> list = new ArrayList<>();for(int i = 0; i < size; i++) {Node node = queue.poll();list.add(node.val);for(Node temp : node.children) {if(temp != null) {queue.add(temp);}}}result.add(list);} return result;}
}

六、515. 在每个树行中找最大值

题目链接:https://leetcode.cn/problems/find-largest-value-in-each-tree-row/description/
思路:没啥东西,就是层序遍历,遍历每一层,然后比较获取最大值。

/*** 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 {public List<Integer> largestValues(TreeNode root) {List<Integer> list = new ArrayList<>();if(root == null) return list;LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();int max = Integer.MIN_VALUE;for(int i = 0; i < size; i++) {TreeNode node = queue.poll();max = Math.max(max, node.val);if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}list.add(max);}return list;}
}

七、116. 填充每个节点的下一个右侧节点指针

题目链接:https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/description/
思路:要求横向连接完美二叉树,本题可以层序遍历,遍历时先添加右子树再添加左子树。也可以使用递归,递归的话,每次递归传入左右两个节点,然后让左节点指向右节点。

/*
// Definition for a Node.
class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, Node _left, Node _right, Node _next) {val = _val;left = _left;right = _right;next = _next;}
};
*/class Solution {public Node connect(Node root) {LinkedList<Node> queue = new LinkedList<>();if(root == null) return root;queue.add(root);while(!queue.isEmpty()) {int size = queue.size();Node p = null;for(int i = 0; i < size; i++) {Node node = queue.poll();node.next = p;p = node;if(node.right != null) queue.add(node.right);if(node.left != null) queue.add(node.left);}}return root;}}

八、117. 填充每个节点的下一个右侧节点指针 II

题目链接:https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/description/
思路:上一题是完全二叉树,可以使用递归来做,本题是普通二叉树,使用层序遍历会简单很多,具体解法和上一题一致。

/*
// Definition for a Node.
class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, Node _left, Node _right, Node _next) {val = _val;left = _left;right = _right;next = _next;}
};
*/class Solution {public Node connect(Node root) {if(root == null) return root;LinkedList<Node> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()) {int size = queue.size();Node p = null;for(int i = 0; i < size; i++) {Node node = queue.poll();node.next = p;p = node;if(node.right != null) queue.add(node.right);if(node.left != null) queue.add(node.left);}}return root;}
}

九、104. 二叉树的最大深度

题目链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/
思路:本题还是使用递归吧,后序遍历直接解决,使用层序遍历,只需要记录层的个数就可以大材小用了。

class Solution {public int maxDepth(TreeNode root) {if(root == null) return 0;int left = maxDepth(root.left);int right = maxDepth(root.right);return Math.max(left, right) + 1;}
}

十、111. 二叉树的最小深度

题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
思路:可以使用递归,用一个全局变量记录最小深度,然后在递归函数的参数中携带当前深度,直接遍历就行了,在叶子节点收集结果。
也可以层序遍历,只需要在每一层层序遍历时,记录叶子节点,只要发现叶子节点即可返回。

class Solution {int min = Integer.MAX_VALUE;public int minDepth(TreeNode root) {if(root == null) return 0;fun(root, 1);return min;}void fun(TreeNode root, int v) {if(root == null) return ;if(root.left == null && root.right == null) {min = Math.min(min, v);return ;}fun(root.left, v+1);fun(root.right, v+1);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/843549.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BUUCTF---web---[BJDCTF2020]ZJCTF,不过如此

1、点开连接&#xff0c;页面出现了提示 传入一个参数text&#xff0c;里面的内容要包括I have a dream。 构造&#xff1a;?/textI have a dream。发现页面没有显示。这里推测可能得使用伪协议 在文件包含那一行&#xff0c;我们看到了next.php的提示&#xff0c;我们尝试读取…

accelerate训练SD-LoRA,解决ValueError: Attempting to unscale FP16 gradients.问题

训练指令需从原来的&#xff1a; accelerate launch –mixed_precision“fp16” train_text_to_image_lora.py –pretrained_model_name_or_path“F:/XYX/Documents/AITools/ControlNetImplement/ControlNetTest/models–runwayml–stable-diffusion-v1-5” –dataset_name“d…

卢文岩博士受邀参与中国科学院大学校友论坛 解码DPU核心价值

近日&#xff0c;第五届中国科学院大学校友创新论坛正式举行&#xff0c;本次论坛聚焦科技前沿领域&#xff0c;旨在搭建高端对话平台&#xff0c;促进产学研深度融合。在大算力时代——AI技术前沿沙龙上&#xff0c;中科驭数高级副总裁、CTO卢文岩博士受邀分享《DPU——连接算…

Mac | Mac 移动硬盘无法分区问题

现象问题 电脑配置&#xff1a;MacBook Pro M1&#xff0c;系统 Sonoma Mac 系统新升级了 Sonoma&#xff0c;结果出现各种问题。外接屏幕居然不能旋转 90 &#xff0c;查了一下是Sonoma系统导致的&#xff0c;以及莫名发热的问题。想着要么回退一下系统算了&#xff0c;于是网…

unity3D获取某天的0点和23点59分59秒

系列文章目录 unity工具 文章目录 系列文章目录unity工具 &#x1f449;一、前言&#x1f449;二、获取某一天的0点和23点59分59秒1-1.代码如下1-2.调用方法如下1-2-1.获取当天的时间1-2-2.获取某一天的时间 &#x1f449;三、当月第一天0时0分0秒&#x1f449;四、当月最后一…

3D点云焊缝提取 平面交线 投影

文章目录 1. 效果2. 思路3. 源码 1. 效果 2. 思路 计算点云法向量&#xff1b;计算点云位姿Pose;翻转Pose中的Z轴方向&#xff0c;使其一致&#xff1b;通过Pose的Z轴对点云进行方向过滤&#xff1b;对点云聚类&#xff1b;根据目标点云的高度提取目标点云&#xff1b;提取两块…

从 0 开始实现一个博客系统 (SSM 项目)

相关技术 Spring Spring Boot Spring MVC MyBatis Html Css JS pom 文件我就不放出来了, 之前用的 jdk8 做的, MySQL 用的 5.7, 都有点老了, 你们自己看着配版本就好 实现功能 用户注册 - 密码加盐加密 (md5 加密)前后端用户信息存储 - 令牌技术用户登录 - (使用 拦截…

外汇天眼:风险预警!以下平台监管牌照被撤销!

监管信息早知道&#xff01;外汇天眼将每周定期公布监管牌照状态发生变化的交易商&#xff0c;以供投资者参考&#xff0c;规避投资风险。如果平台天眼评分过高&#xff0c;建议投资者谨慎选择&#xff0c;因为在外汇天眼评分高不代表平台没问题&#xff01; 以下是监管牌照发生…

DISCO: Disentangled Control for Realistic Human Dance Generation

NTU&Microsoft CVPR24https://github.com/Wangt-CN/DisCo 问题引入 提高human motion transfer模型的泛化性&#xff1b;给出 f , g f,g f,g作为参考图片的前背景&#xff0c;然后给出单个pose p p t pp_t ppt​或者pose序列 p { p 1 , p 2 , ⋯ , p T } p \{p_1,p_2…

Python项目开发实战:五子棋游戏(案例教程)

一、引言 五子棋,又称连珠、连五棋、五目棋、五目碰、五格棋、五石棋、五福棋、五子围棋、串珠棋或五连棋,是一种两人对弈的纯策略型棋类游戏。五子棋的玩法简单,容易上手,但变化多端,深受人们喜爱。本文将详细介绍如何使用Python来开发一个五子棋游戏。 二、需求分析 1.棋…

流水账(CPU设计实战)——lab3

Lab3 Rewrite V1.0 版本控制 版本描述V0V1.0相对V0变化&#xff1a; 修改了文件名&#xff0c;各阶段以_stage结尾&#xff08;因为if是关键词&#xff0c;所以module名不能叫if&#xff0c;遂改为if_stage&#xff0c;为了统一命名&#xff0c;将所有module后缀加上_stage&a…

杭州威雅学校:在学业与生活平衡中找到更好的自己

进入威雅杭州校园&#xff0c; 沿湖边小道步行约5分钟&#xff0c; 四栋寄宿学院与教学区隔湖相望&#xff0c; 威雅人更喜欢叫他们&#xff1a; 「Cavell」&「Dove」 「Elgar」&「Hawking」 提起「寄宿制」&#xff0c;人们本能地会把它和「住校」划等号。 这种…

css中实现背景方格

background: rgba(241,241,241,0.1); background-image:linear-gradient(90deg, rgba(241,243,244,1) 10%, transparent 0),linear-gradient(rgba()241,243,244,1 10%, transparent 0); background-size: 10px 10px; 表现出来的样子就是这个样子

96.网络游戏逆向分析与漏洞攻防-ui界面的设计-角色管理功能的界面设计

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 如果看不懂、不知道现在做的什么&#xff0c;那就跟着做完看效果&#xff0c;代码看不懂是正常的&#xff0c;只要会抄就行&#xff0c;抄着抄着就能懂了 内容…

机器之心 | 清华接手,YOLOv10问世:性能大幅提升,登上GitHub热榜

本文来源公众号“机器之心”&#xff0c;仅用于学术分享&#xff0c;侵权删&#xff0c;干货满满。 原文链接&#xff1a;清华接手&#xff0c;YOLOv10问世&#xff1a;性能大幅提升&#xff0c;登上GitHub热榜 相同性能情况下&#xff0c;延迟减少 46%&#xff0c;参数减少 2…

超市进销存|基于SprinBoot+vue的超市进销存系统(源码+数据库+文档)

超市进销存系统 目录 基于SprinBootvue的超市进销存系统 一、前言 二、系统设计 三、系统功能设计 1 登录注册 2 管理员功能模块 3员工功能模块 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&#xff1a; 博主介绍&#x…

CentOS7安装MySQL教程

第一章 检查是否安装了Mysql 1.1 yum检查 yum list installed | grep mysql 1.2 安装则直接删除 yum remove xxx 1.3 rpm检查 rpm -qa | grep -i mysql # 有则直接删除 rpm -e --nodeps xxx 第二章 正式安装MySQL 2.1 yum安装&#xff0c;下载mysql wget --no-check-ce…

多系统集成的项目周期为何普遍较长?

在现代企业的运营中&#xff0c;各种信息系统的集成已成为提升效率和竞争力的关键。然而&#xff0c;当工厂的ERP系统需要与MES、SRM、WMS、CRM等其他系统集成时&#xff0c;项目周期往往长达一年以上&#xff0c;这不仅耗费时间、人力和财力&#xff0c;还可能影响企业的正常运…

开发者的福音:免去搭建服务,让你的应用开发变得像吃蛋糕一样简单!

传统应用开发的"噩梦" 想象一下&#xff0c;你正在准备一场盛大的晚宴&#xff0c;但必须从零开始建造厨房、种植食材、甚至学习烹饪技巧。这就是传统应用开发的现状——你不仅要设计数据库、编写API接口&#xff0c;还要处理对象存储、实时数据库、云数据库等一系列…

常见的数据分析方法

1.周期性分析法 一个指标的观察时间拉长,看它是否有周期变化规律。周期性分析常见的有两者:自然周期和生命周期。自然周期,指业务指标会随着时间自然变化,如节假日用户/业绩出现下滑、产品销售额随季节变动等;生命周期,譬如“商品生命周期”、“APP生命周期”、“用户生…