將給定的一系列數字插入初始爲空的AVL樹,請你輸出最後生成的AVL樹的根結點的值。
輸入格式:
輸入的第一行給出一個正整數N(≤20),隨後一行給出N個不同的整數,其間以空格分隔。
輸出格式:
在一行中輸出順序插入上述整數到一棵初始爲空的AVL樹後,該樹的根結點的值。
輸入樣例1:
5
88 70 61 96 120
輸出樣例1:
70
輸入樣例2:
7
88 70 61 96 120 90 65
輸出樣例2:
88
#include <iostream>
using namespace std;
struct Node {
int data;
Node* lc;
Node* rc;
};
int height(Node* T) {
return T == NULL ? 0 : max(height(T->lc), height(T->rc)) + 1;
}
Node* turn1(Node* T) { //單向右旋
Node* A = T->lc;
T->lc = A->rc;
A->rc = T;
return A;
}
Node* turn2(Node* T) { //單向左旋
Node* A = T->rc;
T->rc = A->lc;
A->lc = T;
return A;
}
Node* turn3(Node* T) { //先左旋後右旋
T->lc = turn2(T->lc);
return turn1(T);
}
Node* turn4(Node* T) { //先右旋後左旋
T->rc = turn1(T->rc);
return turn2(T);
}
Node* Insert(Node* T, int x) {
if (!T)
T = new Node({ x,NULL,NULL });
else if (x < T->data) {
T->lc = Insert(T->lc, x);
if (height(T->lc) - height(T->rc) == 2)
T = (x < T->lc->data ? turn1(T) : turn3(T));
}
else if (x > T->data) {
T->rc = Insert(T->rc, x);
if (height(T->lc) - height(T->rc) == -2)
T = (x > T->rc->data ? turn2(T) : turn4(T));
}
return T;
}
int main() {
Node* Tree = NULL;
int n, t;
cin >> n;
while (n--) {
cin >> t;
Tree = Insert(Tree, t);
}
cout << Tree->data << endl;
return 0;
}