当前位置:网站首页>二叉树——110. 平衡二叉树
二叉树——110. 平衡二叉树
2022-07-25 23:55:00 【向着百万年薪努力的小赵】
1 题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
2 题目示例


示例 3:
输入:root = []
输出:true
3 题目提示
树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104
4 思路
这道题中的平衡二叉树的定义是:二叉树的每个节点的左右子树的高度差的绝对值不超过 11,则二叉树是平衡二叉树。根据定义,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树,因此可以使用递归的方式判断二叉树是不是平衡二叉树,递归的顺序可以是自顶向下或者自底向上。

有了计算节点高度的函数,即可判断二叉树是否平衡。具体做法类似于二叉树的前序遍历,即对于当前遍历到的节点,首先计算左右子树的高度,如果左右子树的高度差是否不超过 11,再分别递归地遍历左右子节点,并判断左子树和右子树是否平衡。这是一个自顶向下的递归的过程。
复杂度分析
时间复杂度:o(n²),其中n是二叉树中的节点个数。最坏情况下,二叉树是满二叉树,需要遍历二叉树中的所有节点,时间复杂度是O(n)。
对于节点p,如果它的高度是d,则 height§最多会被调用d次(即遍历到它的每一个祖先节点时)。对于平均的情况,一棵树的高度h满足O(h)= O(logn),因为d<h,所以总时间复杂度为O(n logn)。对于最坏的情况,二叉树形成链式结构,高度为O(n),此时总时间复杂度为o(n²)。
空间复杂度:O(n),其中n是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过n。
5 我的答案
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(height(root.left), height(root.right)) + 1;
}
}
}
边栏推荐
- Zhiniu stock -- 09
- 行为型模式之迭代器模式
- Storage of data in memory
- Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution
- 调用钉钉api报错:机器人发送签名过期;solution:签名生成时间和发送时间请保持在 timestampms 以内
- Qpprogressbar for QT style (QSS) application
- Leetcode 0136. numbers that appear only once: XOR
- 浅识 OWASP
- 【MUDUO】EventLoopThreadPool
- 你还在用浏览器自带书签?这款书签插件超赞
猜你喜欢

Vscode format JSON file

死信队列 和消息TTL过期代码

行为型模式之观察者模式

Zhiniu stock -- 09

Practical experience of pair programming

红娘的话

Redis extended data type (jump table /bitmaps/hyperloglog/geospatial)

Payment terms in SAP message No. vg202 IDoc e1edk18 have been transferred: check data

BOM 浏览器对象模型
![[Muduo] EventLoop event cycle](/img/80/824c7061d58796d454be0c438e257c.png)
[Muduo] EventLoop event cycle
随机推荐
Several ways of writing strings in reverse order
Article 75: writing skills of academic papers
Data intensive application system design - Application System Overview
QT smart pointer error prone point
SIGIR '22 recommendation system paper graph network
Unexpected dubug tricks
[testing technology automated testing pytest] basic summary of pytest
redis-扩展数据类型(跳跃表/BitMaps/HyperLogLog/GeoSpatial)
Loading process such as reflection
arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置
模式之固定与交替顺序执行
赋值时'1和'b1有什么区别
面试重点——传输层的TCP协议
What is inode? It will help you understand inode and what help inode provides when creating and deleting files.
Firewall command simple operation
The GUI interface of yolov3 (simple, image detection)
Read the field status of account in ABAP code (hidden, optional, required)
Anti shake and throttling
Find the cause of program dead cycle through debugging
Shardingsphere data slicing