当前位置:网站首页>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;
}
边栏推荐
- Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
- 虚拟串口模拟器和串口调试助手使用教程「建议收藏」
- Dataframe gets the number of words in the string
- String类
- Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
- Buuctf gold III
- 【观察】数字化时代的咨询往何处走?软通咨询的思与行
- 判断一棵二叉树是否为平衡二叉树
- Today, at 14:00, 15 ICLR speakers from Hong Kong University, Beihang, Yale, Tsinghua University, Canada, etc. continue!
- Redis 分布式锁
猜你喜欢

Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)

Leetcode 77 combination -- backtracking method

Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers

How to maintain the laptop battery

Dataframe gets the number of words in the string

Flux d'entrées / sorties et opérations de fichiers en langage C
![[nodemon] app crashed - waiting for file changes before starting... resolvent](/img/ee/9830afd86e092851a2a906cb994949.png)
[nodemon] app crashed - waiting for file changes before starting... resolvent

Activity的生命周期和启动模式详解

Kali install Nessus

Guide for high-end programmers to fish at work
随机推荐
Go language source level debugger delve
Tutorial on the principle and application of database system (002) -- MySQL installation and configuration: MySQL software uninstallation (Windows Environment)
苹果自研基带芯片再次失败,说明了华为海思的技术领先性
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
sql刷题586. 订单最多的客户
今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
sql刷题1050. 合作过至少三次的演员和导演
String类
Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
接口测试框架中的鉴权处理
Comprehensively view the value of enterprise digital transformation
Leetcode 77 combination -- backtracking method
Go 语言错误处理为什么更推荐使用 pkg/errors 三方库?
Template engine velocity Foundation
[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum
Research and investment strategy report of neutral protease industry in China (2022 Edition)
Why is the pkg/errors tripartite library more recommended for go language error handling?
【直播预约】数据库OBCP认证全面升级公开课
Tutorial on the principle and application of database system (003) -- MySQL installation and configuration: manually configure MySQL (Windows Environment)
Sword finger offer II 015 All modifiers in the string