9.5 平衡二叉树
9.5 平衡二叉树
http://codeup.hustoj.com/contest.php?cid=100000614
A 二叉排序树

题目解析
注意函数L、R、insert的写法,⚠️有&
❗️不要在search返回true/false,这里WA了半天,这样最终只能返回false,大概因为search本身就是递归的
代码
#include <cstdio>
#include <algorithm>
using namespace std;
struct node {
int data;
int height;
node *lchild;
node *rchild;
};
int getHeight(node *root) {
if (root == NULL) return 0;
return root->height;
}
//结点的高度等于左右子树的最大高度+1 ⚠️要加1!!!
void updateHeight(node *root) {
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
//平衡因子 = 左右子树高度差
int getBananceFactor(node *root) {
return getHeight(root->lchild) - getHeight(root->rchild);
}
void R(node *&root) { //注意&
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void L(node *&root) { //注意&
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node *&root, int x) {
if (root == NULL) {
root = new node;
root->data = x;
root->height = 1;
root->lchild = root->rchild = NULL;
return;
}
//往左子树插,导致左子树高度>右子树高度
if (x <= root->data) {
insert(root->lchild, x);
updateHeight(root);
if (getBananceFactor(root) == 2) {
if (getBananceFactor(root->lchild) == 1) { //LL
R(root);
} else if (getBananceFactor(root->lchild) == -1) { //LR
L(root->lchild);
R(root);
}
}
} else {
insert(root->rchild, x);
updateHeight(root);
if (getBananceFactor(root) == -2) {
if (getBananceFactor(root->rchild) == -1) { //RR
L(root);
} else if (getBananceFactor(root->rchild) == 1) { //RL
R(root->rchild);
L(root);
}
}
}
}
node *create(int n) {
node *root = NULL;
int temp;
for (int i = 0; i < n; i++) {
scanf("%d", &temp);
insert(root, temp);
}
return root;
}
void search(node *root, int x) {
if (root == NULL) {
printf("0");
return;
}
if (x == root->data) {
printf("1");
return;
} else if (x < root->data) search(root->lchild, x);
else search(root->rchild, x);
}
void preOrder(node *root) {
if (root == NULL) return;
preOrder(root->lchild);
preOrder(root->rchild);
}
void inOrder(node *root) {
if (root == NULL) return;
inOrder(root->lchild);
inOrder(root->rchild);
}
int main() {
int n, k, temp;
while (scanf("%d%d", &n, &k) != EOF) {
node *root = create(n);
for (int i = 0; i < k; i++) {
scanf("%d", &temp);
search(root, temp);
if (i < k - 1) printf(" ");
else printf("\n");
}
}
return 0;
}
本文作者:Joey-Wang
本文链接:https://www.cnblogs.com/joey-wang/p/14541185.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步