当前位置:网站首页>Leetcode刷题——一些用层次遍历解决的问题(111. 二叉树的最小深度、104. 二叉树的最大深度、226. 翻转二叉树、剑指 Offer 27. 二叉树的镜像)
Leetcode刷题——一些用层次遍历解决的问题(111. 二叉树的最小深度、104. 二叉树的最大深度、226. 翻转二叉树、剑指 Offer 27. 二叉树的镜像)
2022-08-03 05:20:00 【lonelyMangoo】
这几道题都是用层次遍历解决的,二叉树遍历记录过二叉树的遍历。
111. 二叉树的最小深度
111. 二叉树的最小深度
最小深度就是从第一层开始往下找,找到第一个叶子结点,就是最小深度
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return 0;
int minDepth = 0;
while (!queue.isEmpty()){
int len = queue.size()-1;
minDepth++;
while (len-->=0){
TreeNode peek = queue.poll();
if(peek.left==null && peek.right==null) return minDepth;
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return minDepth;
}

104. 二叉树的最大深度
104. 二叉树的最大深度
就是返回层数。
public int maxDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return 0;
int depth = 0;
while (!queue.isEmpty()){
depth++;
int len = queue.size()-1;
while (len-->=0){
TreeNode peek = queue.poll();
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return depth;
}

貌似用递归效率更高
public int maxDepth(TreeNode root) {
if(root!=null){
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
if(leftDepth>rightDepth) return leftDepth+1;
else return rightDepth+1;
}
return 0;
}

226. 翻转二叉树
下面这两道题是一样的
226. 翻转二叉树
剑指 Offer 27. 二叉树的镜像
遍历每一个节点,交换左右子树。
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return null;
while (!queue.isEmpty()){
int len = queue.size()-1;
while (len-->=0){
TreeNode peek = queue.poll();
if (peek!=null)swap(peek);
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return root;
}
public static void swap(TreeNode root) {
TreeNode temp =root.left;
root.left = root.right;
root.right = temp;
}


总结
很多简单的问题都能通过层次遍历解决,较难的就要通过递归了.
边栏推荐
猜你喜欢
随机推荐
web安全-SSTI模板注入漏洞
Sqli-labs-master shooting range 1-23 customs clearance detailed tutorial (basic)
用C语言来实现五子棋小游戏
HarmonyOS应用开发第一次培训
Pr第二次培训笔记
7.16(6)
Browser multi-threaded off-screen rendering, compression and packaging scheme
3559. 围圈报数
机器码介绍
MySQL 索引详解和什么时候创建索引什么时候不适用索引
浅谈函数递归汉诺塔
Go (二) 函数部分1 -- 函数定义,传参,返回值,作用域,函数类型,defer语句,匿名函数和闭包,panic
Kaggle 入门(Kaggle网站使用及项目复现)
Greetings(状压DP,枚举子集转移)
Go (一) 基础部分2 -- if条件判断,for循环语句
下拉框数据字典应用案例
一维数组和二维数组的命名以及存储空间
docker mysql 容器中执行mysql脚本文件并解决乱码
Flask,3-6
MySQL 优化建议详解








