当前位置:网站首页>【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
边栏推荐
- Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
- Coding style: SSM environment in MVC mode, code hierarchical management
- Important components of Apache Hadoop
- Notes on Python cookbook 3rd (2.2): String start or end match
- SQL intercepts the data before and after the '.'
- Ineuos industrial interconnection platform, web configuration (ineuview) increases the function of importing and exporting engineering views, as well as optimization and repair. Release: v3.2.1
- Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
- lodash.js源码-flatten
- Self writing performance testing tool (2)
- 利用尾巴作为时间序列进行处理来识别鲸鱼
猜你喜欢

CUDA_存储器模型

Raspberry pie drum set WiFi

Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom

解决Coursera视频无法观看的三种方法(亲测有效)

飞鸽传书局域网找不到其他人的问题解决

If you need a million objects

函数计算进阶-IP查询工具开发

Functional guide for temporary users and novices of PL / SQL developer

推动中国制造升级,汽车装配车间生产流水线 3D 可视化

Visit 2020 PG Technology Conference
随机推荐
CUDA_常量内存
asp.net core中使用Serilog以及自定义Enricher
SRM系统是什么系统?SRM供应商管理系统功能
Operation and design of rights management in ERP
Gets the property value of a column in the list collection object
Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
将Map中对应的key和value赋值到对象中
Prometheus安装配置
mongodb内核源码实现、性能调优、最佳运维实践系列-command命令处理模块源码实现一
delete、truncate、drop 有什么区别,误删数据怎么办
C++ exception implementation mechanism
Ineuos industrial interconnection platform, web configuration (ineuview) increases the function of importing and exporting engineering views, as well as optimization and repair. Release: v3.2.1
爱康国宾怒斥国信证券报告失实,已发律师函
CUDA_获取指定设备
Usage of [:] and [::] in Python
The problem of looting by leetcode
Promote China manufacturing upgrade, 3D visualization of production line in automobile assembly workshop
Error running app:Default Activity not found 解决方法
假如需要一百万个对象
Validation failed for one or more entities. See ‘EntityValidationErrors’解决方法