输入一串数字构建二叉平衡树,套用建树的固定模板
思路,每次插入一个数字就检查一下二叉树是否平衡,决定是否左旋右旋
插入节点模板:
void insert(node * &root, int v) {
if (root == NULL) {
root = newnode(v);
return;
}
if (v < root->v) {
insert(root->lchild, v);
updatahegiht(root);
if (getbalancefac(root) == 2) {
if (getbalancefac(root->lchild) == 1) { //LL
R(root);
}
else if (getbalancefac(root->lchild) == -1) { //LR
L(root->lchild);
R(root);
}
}
}
else {
insert(root->rchild, v);
updatahegiht(root);
if (getbalancefac(root) == -2) {
if (getbalancefac(root->rchild) == -1) { //RR
L(root);
}
else if (getbalancefac(root->rchild) == 1) { //RL
R(root->rchild);
L(root);
}
}
}
}
左旋模板:
//左旋
void L(node * &root) {
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updatahegiht(root);
updatahegiht(temp);
root = temp;
}
右旋模板:
//右旋
void R(node * &root) {
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updatahegiht(root);
updatahegiht(temp);
root = temp;
}
ans:
struct node {
int v, height;
node *lchild, *rchild;
} *root;
node *newnode(int v) {
node *Node = new node;
Node->v = v;
Node->height = 1;
Node->lchild = Node->rchild = NULL;
return Node;
}
int getHeight(node *root) {
if (root == NULL) {
return 0;
}
return root->height;
}
void updatahegiht(node *root) {
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
int getbalancefac(node *root) {
return getHeight(root->lchild) - getHeight(root->rchild);
}
//左旋
void L(node * &root) {
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updatahegiht(root);
updatahegiht(temp);
root = temp;
}
//右旋
void R(node * &root) {
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updatahegiht(root);
updatahegiht(temp);
root = temp;
}
void insert(node * &root, int v) {
if (root == NULL) {
root = newnode(v);
return;
}
if (v < root->v) {
insert(root->lchild, v);
updatahegiht(root);
if (getbalancefac(root) == 2) {
if (getbalancefac(root->lchild) == 1) { //LL
R(root);
}
else if (getbalancefac(root->lchild) == -1) { //LR
L(root->lchild);
R(root);
}
}
}
else {
insert(root->rchild, v);
updatahegiht(root);
if (getbalancefac(root) == -2) {
if (getbalancefac(root->rchild) == -1) { //RR
L(root);
}
else if (getbalancefac(root->rchild) == 1) { //RL
R(root->rchild);
L(root);
}
}
}
}
int main() {
int n, v;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &v);
insert(root, v);
}
printf("%d\n", root->v);
return 0;
}