当前位置:网站首页>leetCode刷题14天二叉树系列之《 110 平衡二叉树判断》
leetCode刷题14天二叉树系列之《 110 平衡二叉树判断》
2022-08-11 03:42:00 【小机double】
leetCode 110 平衡二叉树判断
题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。
示例
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
题目解析
与平衡二叉树等基础相关的可以看《数据结构之二叉树和平衡二叉树的实现》,根据题目的意思,我们需要对每个节点判断其左右子树的高度,并保证其高度差不超过1,即每个节点的平衡因子不超过1,如果查过1的话就不是平衡二叉树了,此时就要进行平衡化操作,不过这并不属于本题要讲述的内容。
其实只要使用递归的方式,并统计左右子树的高度来比较即可,代码如下:
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (!isBalanced(root.left) || !isBalanced(root.right)) {
//如果有左右子树不满足平衡二叉树条件则返回false
return false;
}
int leftDepth = maxDepth(root.left) + 1;
int rightDepth = maxDepth(root.right) + 1;
if (Math.abs(leftDepth - rightDepth) > 1) {
return false;
}
return true;
}
public int maxDepth(TreeNode root) {
//计算每颗树的最高深度
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
有代码可以看出,这其实是从底向上来判断一整颗树是否是平衡二叉树。
程序运行结果:
边栏推荐
- Leetcode 450. 删除二叉搜索树中的节点
- 互换性测量技术-几何误差
- Day20 FPGA 】 【 - block the I2C read and write EEPROM
- What has programmatic trading changed?
- 高校就业管理系统设计与实现
- AI+Medical: Using Neural Networks for Medical Image Recognition and Analysis
- Roewe imax8ev cube battery security, what blackening and swelling are hidden behind it?
- 二叉树相关代码题【较全】C语言
- pathman_config、pathman_config_params 删除后,如何重建?
- MYSQLg高级------聚簇索引和非聚簇索引
猜你喜欢
随机推荐
A large horse carries 2 stone of grain, a middle horse carries 1 stone of grain, and two ponies carry one stone of grain. It takes 100 horses to carry 100 stone of grain. How to distribute it?
QueryDet: Cascading Sparse Query Accelerates Small Object Detection at High Resolution
常用认证机制
E-commerce project - mall time-limited seckill function system
Day20 FPGA 】 【 - block the I2C read and write EEPROM
LeetCode热题(12.买卖股票的最佳时机)
rac备库双节点查询到的表最后更新时间不一致
typedef定义结构体数组类型
【愚公系列】2022年08月 Go教学课程 036-类型断言
How to delete statements audit log?
I didn't expect MySQL to ask these...
机器学习是什么?详解机器学习概念
[BX] and loop
Talk about the understanding of RPC
互换性与测量技术-公差原则与选用方法
“顶梁柱”滑坡、新增长极难担重任,阿里“蹲下”是为了跳更高?
The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
浮点数在内存中的存储方式
80端口和443端口是什么?有什么区别?
Rotary array problem: how to realize the array "overall reverse, internal orderly"?"Three-step conversion method" wonderful array