輸入格式
第一行包含整數 N,表示總插入值數量。第二行包含 N 個不同的整數,表示每個插入值。
輸出格式
輸出得到的 AVL 樹的根是多少。
數據范圍
1≤N≤20
輸入樣例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;
const int N=30;
int l[N],r[N],v[N],h[N],idx;
int n,root;
int height(int u)
{return h[l[u]]-h[r[u]];
}
void update(int u)
{h[u]=max(h[l[u]],h[r[u]])+1;
}
void R(int &u)
{int p=l[u];l[u]=r[p];r[p]=u;update(u),update(p);u=p;
}
void L(int &u)
{int p=r[u];r[u]=l[p];l[p]=u;update(u),update(p);u=p;
}
void insert(int &u,int w)
{if(!u) u=++idx,v[u]=w;else if(w<v[u]){insert(l[u],w);if(height(u)==2){if(height(l[u])==1) R(u);else L(l[u]),R(u);}}else{insert(r[u],w);if(height(u)==-2){if(height(r[u])==-1) L(u);else R(r[u]),L(u);}}update(u);
}
int main()
{cin>>n;while(n--){int w;cin>>w;insert(root,w);}cout<<v[root];return 0;
}