当前位置:网站首页>【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
边栏推荐
- JMeter的简单使用
- DB engines database ranking in November: PostgreSQL holds the top spot in the same period
- Error running app:Default Activity not found 解决方法
- Simple use of JMeter
- Coding style: SSM environment in MVC mode, code hierarchical management
- Error running app: default activity not found solution
- What is the SRM system? SRM supplier management system functions
- 解决Coursera视频无法观看的三种方法(亲测有效)
- 自己上手写性能测试工具(二)
- How much is the cost of CRM system?
猜你喜欢
Gets the property value of a column in the list collection object
树莓派鼓捣记 - 设置 wifi
恒讯科技浅谈:出现服务器宕机的处理方式
关于centos启动报错:Failed to start Crash recovery kernel arming的解决方案
飞鸽传书局域网找不到其他人的问题解决
Aikang Guobin denounced Guoxin Securities report as untrue and sent a lawyer's letter
ES6, ES7, es8 Learning Guide
对于程序员,那些既陌生又熟悉的计算机硬件
Seam engraving algorithm: a seemingly impossible image size adjustment method
推动中国制造升级,汽车装配车间生产流水线3D可视化
随机推荐
Python中[:]与[::]的用法
2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...
iNeuOS工业互联平台,WEB组态(iNeuView)增加工程视图导入、导出功能,及优化和修复,发布:v3.2.1版本
会展云技术解读 | 面对突发事故,APP 如何做好崩溃分析与性能监控?
接缝雕刻算法:一种看似不可能的图像大小调整方法
JT Jingtao project
Validation failed for one or more entities. See 'entityvalidationerrors' solution
IP address SSL certificate
自己上手写性能测试工具(二)
大专学历的我工作六年了,还有机会进大厂吗?
《Python Cookbook 3rd》笔记(2.2):字符串开头或结尾匹配
If you need a million objects
将Map中对应的key和value赋值到对象中
Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法
One image can hold 16x16 words! ——Transformers for large scale image scaling recognition (a brief review of ICLR 2021 papers)
C++异常实现机制
Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
Mongodb kernel source code implementation, performance tuning, best operation and maintenance practice series command processing module source code implementation 1
CUDA常用概念及注意点
CUDA_寄存器和局部存储器