当前位置:网站首页>【LeetCode】 93 平衡二叉树
【LeetCode】 93 平衡二叉树
2020-11-10 01:15:00 【JaneRoad】
题目:


解题思路:
自底向上的递归
类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 -1−1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。
代码:
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
版权声明
本文为[JaneRoad]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4248053/blog/4710406
边栏推荐
- November 09, 2020: talk about the similarities and differences between the bulon filter and the cuckoo filter?
- Visit 2020 PG Technology Conference
- 推动中国制造升级,汽车装配车间生产流水线 3D 可视化
- Unity使用transform.Rotate进行三维旋转角度出现偏差
- Assign the corresponding key and value in the map to the object
- 对于程序员,那些既陌生又熟悉的计算机硬件
- 编码风格:Mvc模式下SSM环境,代码分层管理
- SQL case conversion, remove the space before and after
- JT Jingtao project
- Function calculation advanced IP query tool development
猜你喜欢

Hand in hand to teach you to use container service tke cluster audit troubleshooting

iNeuOS工业互联平台,WEB组态(iNeuView)增加工程视图导入、导出功能,及优化和修复,发布:v3.2.1版本

mongodb内核源码实现、性能调优、最佳运维实践系列-command命令处理模块源码实现一

Fire knowledge online answer activity small program

Coding style: SSM environment in MVC mode, code hierarchical management

An unsafe class named unsafe

Common settings of PLSQL developer

Can't find other people's problem to solve

Youtube订阅——解决在弹窗内使用Youtube订阅按钮高度显示不全的问题

Must see! RDS database all in one
随机推荐
将Map中对应的key和value赋值到对象中
Detach ()
js label语法跳出多重循环
Validation failed for one or more entities. See 'entityvalidationerrors' solution
会展云技术解读 | 面对突发事故,APP 如何做好崩溃分析与性能监控?
Unity使用transform.Rotate进行三维旋转角度出现偏差
完美日记母公司逸仙电商招股书:重营销、轻研发,前三季度亏11亿
Youtube订阅——解决在弹窗内使用Youtube订阅按钮高度显示不全的问题
CUDA_获取指定设备
C++ exception implementation mechanism
Experiment 2
delete、truncate、drop 有什么区别,误删数据怎么办
Error running app:Default Activity not found 解决方法
[leetcode] 92 integer inversion
Mongodb index management of distributed document storage database
So what should investors do with the current market? Now a new investment outlet is coming!
SRM系统是什么系统?SRM供应商管理系统功能
函数计算进阶-IP查询工具开发
Coding style: SSM environment in MVC mode, code hierarchical management
C/C++编程笔记:C语言开发坦克大战!纪念我们逝去的小霸王游戏