LeetCode(110) Balanced Binary Tree
2024-09-01 09:22:14
题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
分析
判断给定二叉树是否为二叉平衡树,即任一节点的左右子树高度差必须小于等于1,只需要求得左右子树的高度,比较判定即可。
AC代码
class Solution {
public:
//判断二叉树是否平衡
bool isBalanced(TreeNode* root) {
if (!root)
return true;
int lheight = height(root->left), rheight = height(root->right);
if (abs(lheight - rheight) <= 1)
return isBalanced(root->left) && isBalanced(root->right);
else
return false;
}
//求树的高度
int height(TreeNode *root)
{
if (!root)
return 0;
else
return max(height(root->left), height(root->right)) + 1;
}
};
最新文章
- Twitter面试题蓄水池蓄水量算法(原创 JS版,以后可能会补上C#的)
- 【写给大家看的CSS】定位元素:使用position/display布局
- SCRUM 流程的步骤2: Spring 计划
- Centos7下dnscrypt-proxy安装
- SQL 订阅发布备注
- rsync+inotify实现远程数据备份
- 【Beta版本】冲刺-Day1
- sum(iterable[, start]) 	对集合求和
- html中子div用了浮动怎样让父div的大小自动撑开(清除浮动)
- canvas图表详解系列(5):雷达(面积)图
- Mysql 查询重复的记录
- python学习笔记(7)
- MongoDB安全使用指引
- Month format:number to English abbre
- P1028 数的计算
- ASP.NET CORE Swagger
- linux命令(及解压tar.gz文件)
- linux shell的for循环语法是怎样的?
- Python Signal 信号
- iOS原生项目集成React Native模块