当前位置:网站首页>【剑指 Offer】55 - II. 平衡二叉树
【剑指 Offer】55 - II. 平衡二叉树
2022-07-01 13:26:00 【LuZhouShiLi】
剑指 Offer 55 - II. 平衡二叉树
题目
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
思路
首先定义一个计算节点高度的函数,然后根据二叉树的前序遍历,对于当前遍历的节点,首先计算左右子树的高度,如果左右子树的高度差是否不超过1,在分别递归遍历左右子节点,并判断左右子树是否平衡。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
int height(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
else
{
// 计算二叉树的高度
return max(height(root->left),height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root)
{
if(root == NULL)
{
return true;
}
else
{
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
边栏推荐
- [安网杯 2021] REV WP
- Professor Li Zexiang, Hong Kong University of science and technology: I'm wrong. Why is engineering consciousness more important than the best university?
- SAP intelligent robot process automation (IRPA) solution sharing
- 详细讲解面试的 IO多路复用,select,poll,epoll
- Investment analysis and prospect prediction report of global and Chinese p-nitrotoluene industry Ⓙ 2022 ~ 2027
- 陈宇(Aqua)-安全-&gt;云安全-&gt;多云安全
- Wave animation color five pointed star loader loading JS special effects
- Application of 5g industrial gateway in scientific and technological overload control; off-site joint law enforcement for over limit, overweight and overspeed
- 开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO
- Nexus builds NPM dependent private database
猜你喜欢
Simple two ball loading
B站被骂上了热搜。。
[machine learning] VAE variational self encoder learning notes
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
Reasons for MySQL reporting 1040too many connections and Solutions
MySQL报错1040Too many connections的原因以及解决方案
SAP 智能机器人流程自动化(iRPA)解决方案分享
流量管理技术
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
焱融看 | 混合云时代下,如何制定多云策略
随机推荐
孔松(信通院)-数字化时代云安全能力建设及趋势
网络中的listen
Flow management technology
关于佛萨奇2.0“Meta Force原力元宇宙系统开发逻辑方案(详情)
JVM有哪些类加载机制?
SAP 智能机器人流程自动化(iRPA)解决方案分享
受益互联网出海 汇量科技业绩重回高增长
04 redis source code data structure dictionary
【241. 为运算表达式设计优先级】
北斗通信模块 北斗gps模块 北斗通信终端DTU
Colorful five pointed star SVG dynamic web page background JS special effect
5. Use of ly tab plug-in of header component
A Fletter version of Notepad
Router. use() requires a middleware function but got a Object
La taille de la pile spécifiée est petite, spécifiée à la sortie 328k
Report on the current situation and development trend of bidirectional polypropylene composite film industry in the world and China Ⓟ 2022 ~ 2028
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
单工,半双工,全双工区别以及TDD和FDD区别
当你真的学会DataBinding后,你会发现“这玩意真香”!
During Oracle CDC data transmission, the CLOB type field will lose its value during update. There is a value before update, but