当前位置:网站首页>字节面试题——判断一棵树是否为平衡二叉树
字节面试题——判断一棵树是否为平衡二叉树
2022-07-26 05:54:00 【学习追求高效率】
字节面试题
4. 判断一棵树 是否为 平衡二叉树(时间复杂度:O(N^2))
*****不用管递归的逻辑,只需根据最上边根节点写出代码即可
// 获取二叉树的高度 时间复杂度:O(N)
int getHeight(TreeNode root) {
if(root == null) return 0;
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
return (leftHeight > rightHeight ?
leftHeight+1 : rightHeight+1);
}
//时间复杂度:O(N^2)
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
return Math.abs(leftHeight-rightHeight) <= 1
&& isBalanced(root.left)
&& isBalanced(root.right);
}
优化,当出现不平衡情况,便不再进行递归,而是依次return -1
优化时候的思考角度,便是从下往上思考
//这个题 是字节考过的原题 O(n)
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftTree = maxDepth(root.left);
int rightTree = maxDepth(root.right);
if(leftTree >= 0 && rightTree >= 0 && Math.abs(leftTree - rightTree) <= 1) {
return Math.max(leftTree,rightTree) + 1;
}else {
return -1;
}
}
public boolean isBalanced2(TreeNode root) {
if(root == null) return true;
return maxDepth(root) >= 0;
}
***** 解决思想
原方法是:求根节点的 左右子树的高度后比较,
然后 再去判断左右子树的子树的分别高度差,这样就会递归两次 时间复杂度为(O N2)
修改方法:是只遍历一次,在求树的高度的时候,判断是否为平衡二叉树,如果不是,便停止计算 便是 O(N)
边栏推荐
- A trick to teach you to easily understand Potter's map
- Ros2 preliminary: basic communication with topic
- Redis official visualization tool, with high appearance value and powerful functions!
- You'd better not take this kind of project!
- 我又发现了超赞的软硬件项目,全部开源
- JS的调用方式与执行顺序
- Lamp architecture
- Mba-day28 concept of number - exercise questions
- 102. (cesium chapter) cesium road streamer
- 高效,可靠,安全的串口通讯开源方案
猜你喜欢
![[personal summary] end of July 24, 2022](/img/9e/dfc37c2684aa8849291817782c947b.png)
[personal summary] end of July 24, 2022

Hack the box - Introduction to networking module detailed Chinese tutorial

vagrant下载速度慢的解决方法

Day110.尚医通:Gateway集成、医院排班管理:科室列表、根据日期统计数据、排班详情

Application and value of IVR in VoIP telephone system

对接微信支付(二)统一下单API

Kingbasees SQL language reference manual of Jincang database (7. Conditional expression)

ES Cluster in Red status: what about write & delete operations?

Redis 官方可视化工具,高颜值,功能真心强大!

Benji Banas launched the second season of earn while playing bonus activities, supporting the use of multiple Benji passes!
随机推荐
Redis persistence AOF
Two auxiliary functions of integral Mall for business user operation
Redis主从复制
Modifiers should be declared in the correct order 修饰符应按正确的顺序声明
Unity Profiler
Unity Profiler
sdc中对cdc的处理方式
Chapter 1 - Construction of development environment
Kingbasees SQL language reference manual of Jincang database (10. Query and sub query)
光量子里程碑:6分钟内解决3854个变量问题
leetcode-aboutString
Jdbc流式查询与游标查询
Debugging sharp weapon! A lightweight log library log.c
How to view the container name in pod
Properties of binary tree~
The refurbishment and counterfeiting of chips have made people feel numb
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十一))
一招教你轻松看懂波特图
vagrant下载速度慢的解决方法
为什么LPDDR不能完全代替DDR?