代码:
#include <iostream>
using namespace std;
enum color{black,red};
struct node{
int data;
node *child[2],*father;
color colour;
node(){
child[1]=child[0]=father=nullptr;
}
}*root;
void clearen(node *pos){
if(pos!=nullptr){
delete pos->child[0];
delete pos->child[1];
delete pos;
return;
}
}
void outqsbl(node *pos){
if(pos!=nullptr){
cout<<"(";
outqsbl(pos->child[0]);
if(pos->colour==red) cout<<"r";
else cout<<"b";
cout<<pos->data;
outqsbl(pos->child[1]);
cout<<")";
}
}
void rotate(node *o,bool lorr){
node *k=o->child[lorr^1];
o->child[lorr^1]=k->child[lorr];
k->child[lorr]=o;
o=k;
return;
}
void insert(int x){
node *pos=root;
if(pos==nullptr){
root=new node;
pos=root;
pos->data=x;
pos->colour=black;
return;
}
do{
int w=0;
if(x<pos->data) w=0;
else w=1;
if(pos->child[w]!=nullptr) pos=pos->child[w];
else{
pos->child[w]=new node;
pos->child[w]->father=pos;
pos=pos->child[w];
pos->data=x;
pos->colour=red;
break;
}
}while(1);
if(pos->father->colour==black) return;
else{
balance:
node *father=pos->father;
node *grandfather=nullptr;
if(father!=nullptr) grandfather=father->father;
node *uncle=nullptr;
if(grandfather!=nullptr){
uncle=grandfather->child[0];
if(uncle==father) uncle=grandfather->child[1];
}
if(uncle!=nullptr && uncle->colour==red){
father->colour=uncle->colour=black;
grandfather->colour=red;
pos=grandfather;
}else if((uncle==nullptr ? false : uncle->colour==black) && father==grandfather->child[0]){
if(pos==father->child[1]){
rotate(father,0);
pos=father;
}
father->colour=black;
grandfather->colour=red;
rotate(grandfather,1);
}else if((uncle==nullptr ? false : uncle->colour==black) && father==grandfather->child[1]){
if(pos==father->child[0]){
rotate(father,1);
pos=father;
}
father->colour=black;
grandfather->colour=red;
rotate(grandfather,0);
}else return;
goto balance;
}
}
bool search(int x){
node *pos=root;
while(pos->data!=x){
if(x<pos->data) pos=pos->child[0];
else pos=pos->child[1];
if(pos==nullptr) return false;
}
return true;
}
int main(){
clearen(root);
int n;
cin>>n;
for(int i=1;i<=n;i++){
int v;
cin>>v;
insert(v);
outqsbl(root);
cout<<endl;
}
for(int i=1;i<=n;i++){
int v;
cin>>v;
cout<<search(v)<<endl;
}
return 0;
}
输入:
8
10 11 9 8 7 6 5 4
c
输出:
(b10)
(b10(r11))
((r9)b10(r11))
(((r8)b9)r10(b11))
((((r7)r8)b9)r10(b11))
(((((r6)r7)r8)b9)r10(b11))
((((((r5)r6)r7)r8)b9)r10(b11))
(((((((r4)r5)r6)r7)r8)b9)r10(b11))
0
0
0
0
0
0
0
0
这是一棵红黑树,但是它根本没有平衡(看括号表示)
请帮忙看下代码出现了什么问题,谢谢!