当前位置:网站首页>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;
}
总结
很多简单的问题都能通过层次遍历解决,较难的就要通过递归了.
边栏推荐
猜你喜欢
随机推荐
Haproxy服务监控
dataframe插入一列
判断回文数
【DC-4靶场渗透】
npm run dev/serve 时报错
【CSRF,SSRF,XXE,PHP反序列化,Burpsuite】
-寻找鞍点-
用C语言来实现扫雷小游戏
Modelarts第一次培训
Sqli-labs-master shooting range 1-23 customs clearance detailed tutorial (basic)
UPC-Longest X
Greetings(状压DP,枚举子集转移)
Go (二) 函数部分1 -- 函数定义,传参,返回值,作用域,函数类型,defer语句,匿名函数和闭包,panic
vivado遇到的问题
网卡软中断过高问题优化总结
breed Web刷机升级详细教材修正编译器固件说明_itkeji.top
【myPow,2次幂,3次幂..代码实现】
MySQL 唯一索引 UNIQUE KEY 会导致死锁?
Kaggle 入门(Kaggle网站使用及项目复现)
Djiango第四次培训笔记