当前位置:网站首页>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;
}


总结
很多简单的问题都能通过层次遍历解决,较难的就要通过递归了.
边栏推荐
猜你喜欢

jsp通过form表单提交数据到servlet报404

【DC-5靶场渗透】

Apache2-XXE vulnerability penetration

1230: 蜂巢

让小程序开发进入 `tailwind jit` 时代

Sqli-labs-master shooting range 1-23 customs clearance detailed tutorial (basic)

Go (二) 函数部分1 -- 函数定义,传参,返回值,作用域,函数类型,defer语句,匿名函数和闭包,panic

icebreaker的垃圾话学习指南

TypeError: Cannot read property ‘xxxx‘ of undefined的解决方法

Djiango第四次培训笔记
随机推荐
自定义封装组件-国际化-下拉搜索
1230: 蜂巢
web安全-命令执行漏洞
一劳永逸解决vs编译器无法使用scanf函数
Newifi路由器第三方固件玩机教程,这个路由比你想的更强大以及智能_Newifi y1刷机_smzdm
7.24[C语言零基础 知识点总结]
让小程序开发进入 `tailwind jit` 时代
Flask的简单介绍及使用方法简介
A-B数对问题|UPC-Count Interval|洛谷-P1102A-B数对
深度学习入门之GRU
Pr第四次培训笔记
vivado遇到的问题
Go (一) 基础部分3 -- 数组,切片(append,copy),map,指针
lintcode2330 · 计算x秒后的时间
网卡软中断过高问题优化总结
【按位取反,逻辑操作符,条件操作符,逗号表达式,下标引用,函数调用,结构体】操作符后续+表达式求值(上)
7.8(6)
web安全-SSTI模板注入漏洞
mysql 存储过程 动态参数 查询执行结果
2.ROS通信机制