当前位置:网站首页>Judge whether a binary tree is a balanced binary tree
Judge whether a binary tree is a balanced binary tree
2022-07-01 16:47:00 【Bright morning light】
1、 subject
Given a binary tree , Judge whether this binary tree is a balanced binary tree .
2、 Ideas
Use the recursive routine of binary tree to solve this problem .
If the X A tree with nodes as roots is a balanced binary tree , Then three conditions must be met :
- The left subtree is balanced
- The right subtree is balanced
- The absolute value of the height difference between the left and right subtrees is less than 2
that X The information that the node needs to get from the left tree :① Is it balanced ;② Height
Empathy ,X The node needs the information obtained from the right tree :① Is it balanced ;② Height
such , We can know whether the tree is balanced .
therefore , Use structure Info Save these two information , Every node is treated equally , Such treatment is required .
3、 Realization
/************************************************************************* > File Name: 034. Determine whether a binary tree is a balanced binary tree .cpp > Author: Maureen > Mail: [email protected] > Created Time: 5、 ... and 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) {
}
};
// Method 1 : recursive
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;
}
// Method 2 : Binary tree recursive routine solution
class Info {
public:
bool isBalanced; // Is it balanced
int height; // 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;
}
边栏推荐
- Preliminary study on golang crawler framework
- Guide for high-end programmers to fish at work
- Comprehensively view the value of enterprise digital transformation
- Rhcsa Road
- PostgreSQL 存储结构浅析
- Origin2018 installation and use (sorting)
- P2592 [zjoi2008] birthday party (DP)
- Stegano in the world of attack and defense
- C語言輸入/輸出流和文件操作
- Mlperf training v2.0 list released, with the same GPU configuration, the performance of Baidu PaddlePaddle ranks first in the world
猜你喜欢

C語言輸入/輸出流和文件操作

Today, at 14:00, 15 ICLR speakers from Hong Kong University, Beihang, Yale, Tsinghua University, Canada, etc. continue!

Internet News: "20220222" get together to get licenses; Many products of Jimi have been affirmed by consumers; Starbucks was fined for using expired ingredients in two stores

【直播预约】数据库OBCP认证全面升级公开课

VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v

Analysis of PostgreSQL storage structure

C language input / output stream and file operation

Sweden announced its decision to exclude Huawei 5g equipment, but Huawei has successfully found a new way out

Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
![[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment](/img/0e/52e37527bc717c7a55741725087bad.png)
[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment
随机推荐
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
模板引擎Velocity 基礎
Rhcsa Road
判断二叉树是否为二叉搜索树
Zabbix2.2 monitoring system and application log monitoring alarm
AI高考志愿填报:大厂神仙打架,考生付费围观
Kali install Nessus
单例模式的懒汉模式跟恶汉模式的区别
sql刷题584. 寻找用户推荐人
Redis 分布式锁
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
红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
SQL question brushing 586 Customers with the most orders
FPN network details
数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)
Is it reliable to open an account on flush with mobile phones? Is there any potential safety hazard
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting
Stegano in the world of attack and defense
判断链表是否是回文链表
Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)