还差删除
功能
#include<iostream>
#include <algorithm>
using namespace std;
struct node{
int w, height; //w为结点权值
node *lchild, *rchild;
};
node* newNode(int w){ //生成一个新节点
node* Node = new node;
Node->w = w;
Node->height = 1;
Node->lchild = Node->rchild = NULL;
return Node;
}
int getHeight(node* root){
if (root == NULL) return 0;
return root->height;
}
int getBF(node* root){ //计算平衡因子
return getHeight(root->lchild) - getHeight(root->rchild);
}
void updateHeight(node* root){
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void L(node* &root){ //左旋
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node* root){ //右旋
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node* &root,int w){ //插入节点
if (root == NULL){
root = newNode(w);
return;
}
if (w < root->w){
insert(root->lchild, w);
updateHeight(root);
if (getBF(root) == 2){
if (getBF(root->lchild) == 1) //LL型
R(root);
else if (getBF(root->lchild) == -1){ //LR型
L(root->lchild);
R(root);
}
}
}
else{
insert(root->rchild, w);
updateHeight(root);
if (getBF(root) == -2){
if (getBF(root->rchild) == -1) //RR型
L(root);
else if (getBF(root->rchild) == 1){ //RL型
R(root->rchild);
L(root);
}
}
}
}
void search(node* root, int w){
if (root == NULL){
cout << "查找失败!" << endl;
return;
}
if (w == root->w)
cout << w << endl;
else if (w < root->w)
search(root->lchild, w);
else if (w > root->w)
search(root->rchild, w);
}
node* create(int data[], int n){
node* root = NULL;
for (int i = 0; i < n; i++)
insert(root, data[i]);
return root;
}
int main()
{
int a[6] = { 3, 6, 1, 8, 7, 9 };
node* root = create(a, 6);
return 0;
}