当前位置:网站首页>判断一棵二叉树是否为平衡二叉树
判断一棵二叉树是否为平衡二叉树
2022-07-01 16:26:00 【明朗晨光】
1、题目
给定一棵二叉树,判断这棵二叉树是不是平衡二叉树。
2、思路
使用二叉树的递归套路解决这个问题。
如果以 X 节点为根的一棵树是平衡二叉树,那么必须满足三个条件:
- 左子树是平衡的
- 右子树是平衡的
- 左右子树的高度差的绝对值小于 2
那么 X 节点需要向左树获取的信息:①是否平衡;②高度
同理,X 节点需要向右树获取的信息:①是否平衡;②高度
这样,就能知道这棵树是否平衡。
所以,使用结构体 Info 保存这两个信息,每个节点一视同仁,都要进行这样的处理。
3、实现
/************************************************************************* > File Name: 034.判断二叉树是否为平衡二叉树.cpp > Author: Maureen > Mail: [email protected] > Created Time: 五 7/ 1 15:07:04 2022 ************************************************************************/
#include <iostream>
#include <ctime>
using namespace std;
class TreeNode {
public:
int value;
TreeNode *left;
TreeNode *right;
TreeNode(int data) : value(data) {
}
};
//方法一:递归
int getHeight(TreeNode *root) {
if (root == nullptr) return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
bool isBalanced1(TreeNode *root) {
if (root == nullptr) return true;
return isBalanced1(root->left)
&& isBalanced1(root->right)
&& abs(getHeight(root->left) - getHeight(root->right)) < 2;
}
//方法二: 二叉树递归套路求解
class Info {
public:
bool isBalanced; //是否平衡
int height; //高度
Info(bool isB, int h) : isBalanced(isB), height(h) {
}
};
Info *process(TreeNode *x) {
if (x == nullptr) {
return new Info(true, 0);
}
Info *leftInfo = process(x->left);
Info *rightInfo = process(x->right);
bool isBalanced = leftInfo->isBalanced && rightInfo->isBalanced && abs(leftInfo->height - rightInfo->height) < 2;
int height = max(leftInfo->height, rightInfo->height) + 1;
return new Info(isBalanced, height);
}
bool isBalanced2(TreeNode *root) {
return process(root)->isBalanced;
}
//for test
TreeNode *generate(int level, int maxLevel, int maxVal) {
if (level > maxLevel || (rand() % 100 /(double)101) < 0.5)
return nullptr;
TreeNode *root = new TreeNode(rand() % maxVal);
root->left = generate(level + 1, maxLevel, maxVal);
root->right = generate(level + 1, maxLevel, maxVal);
return root;
}
TreeNode *generateRandomBST(int maxLevel, int maxVal) {
return generate(1, maxLevel, maxVal);
}
int main() {
srand(time(0));
int maxLevel = 5;
int maxVal = 100;
int testTime = 1000001;
for (int i = 0; i < testTime; i++) {
TreeNode *root = generateRandomBST(maxLevel, maxVal);
//cout << "isBalanced1(root) = " << isBalanced1(root) << endl;
//cout << "isBalanced2(root) = " << isBalanced2(root) << endl;
if (isBalanced1(root) != isBalanced2(root)) {
cout << "Oops!" << endl;
break;
}
}
cout << "finish!" << endl;
return 0;
}
边栏推荐
- Learn selenium to simulate mouse operation, and you can be lazy a little bit
- Basic use of MySQL
- sql刷题1050. 合作过至少三次的演员和导演
- 独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
- Rhcsa Road
- How to solve the problem that the battery icon of notebook computer does not display
- Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
- How does go use symmetric encryption?
- Principes et applications du système de base de données (006) - - compilation et installation de MySQL 5.7 (environnement Linux)
- What are the differences between PHP and DW
猜你喜欢

Template engine velocity Foundation

Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership

Comprehensively view the value of enterprise digital transformation

制造业数字化转型究竟是什么

sql刷题584. 寻找用户推荐人

How to use F1 to F12 correctly on laptop keyboard

Tutorial on principles and applications of database system (006) -- compiling and installing MySQL 5.7 (Linux Environment)

巴比特 | 元宇宙每日必读:奈雪币、元宇宙乐园、虚拟股票游戏...奈雪的茶这波“操作拉满”的营销活动你看懂了吗?...

Is the programmer's career really short?

How to repair the laptop that cannot connect to the wireless network
随机推荐
[live broadcast appointment] database obcp certification comprehensive upgrade open class
How to optimize repeated if err in go language= Nil template code?
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
Leetcode 77 combination -- backtracking method
[daily question] 1175 Prime permutation
Zabbix2.2监控之系统及应用日志监控报警
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
Rhcsa Road
Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
How to cancel automatic search and install device drivers for laptops
Problems encountered in IM instant messaging development to maintain heartbeat
Tutorial on principles and applications of database system (006) -- compiling and installing MySQL 5.7 (Linux Environment)
Sqlserver query: when a.id is the same as b.id, and the A.P corresponding to a.id cannot be found in the B.P corresponding to b.id, the a.id and A.P will be displayed
Guide for high-end programmers to fish at work
Basic use of MySQL
[JetsonNano] [教程] [入门系列] [三] 搭建TensorFlow环境
China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District
StoneDB 为国产数据库添砖加瓦,基于 MySQL 的一体化实时 HTAP 数据库正式开源!
Advantages, values and risks of chain games compared with traditional games
Preliminary study on golang crawler framework