1066. Root of AVL Tree (25)
阿新 • • 發佈:2018-03-08
組合 png 必須 數組 eight pac image spa span
距離PAT考試還有 11天最重要的是做透每一題
(1)思路
就是考察基本的AVL樹
這裏主要寫的是單旋轉左旋和右旋
雙旋轉可以用其組合得到
這裏要註意的是,insert,roatewithleftchild和roatewithrightchild函數都是傳的引用,root初始化為0,表示插入的位置到了
所以root的值會不斷改變為當前樹的根
按照這個思路必須將left,right數組初始為零
順便為了好看,可以規定height[0]為-1
#include <cstdio> #include <vector> #include<cstring> #include <algorithm> using namespace std; int n; int num=0; const int N=30; int a[N]; int left[N]; int right[N]; int height[N]; int newnode(int x) { num++; a[num]=x; left[num]=0; right[num]=0; height[num]=0; return num; } void roatewithleftchild(int& p) { int q=left[p]; left[p]=right[q]; right[q]=p; height[p]=max(height[left[p]],height[right[p]])+1; height[q]=max(height[left[q]],height[p]); p=q; } void roatewithrightchild(int& p) { int q=right[p]; right[p]=left[q]; left[q]=p; height[p]=max(height[left[p]],height[right[p]])+1; height[q]=max(height[right[q]],height[p]); p=q; } void insert(int x,int& p) { if(!p) p=newnode(x); else if(x < a[p]){ insert(x,left[p]); // if(height[left[p]] - height[right[p]] == 2) { if(x < a[left[p]]) roatewithleftchild(p); else { roatewithrightchild(left[p]); roatewithleftchild(p); } } } else if(x > a[p]) { insert(x,right[p]); if(height[right[p]] - height[left[p]] == 2) { if(x > a[right[p]]) roatewithrightchild(p); else {//left-right roate roatewithleftchild(right[p]); roatewithrightchild(p); } } } height[p]=max(height[left[p]],height[right[p]])+1; } int main() { scanf("%d",&n); memset(a,0,sizeof(a)); memset(left,0,sizeof(left)); memset(right,0,sizeof(right)); memset(height,-1,sizeof(height)); int root=0; for(int i=0;i<n;i++) { int v; scanf("%d",&v); insert(v,root); } printf("%d\n",a[root]); return 0; }
1066. Root of AVL Tree (25)