1066 Root of AVL Tree(平衡二叉树/自平衡二叉查找树/AVL树)
题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888
大致题意就是给出一个包含N个元素的序列,构建一个平衡二叉树,然后输出根结点上的元素。
这是一道模板题,要记住大体流程,然后反复练习。
PS:连同7行注释,一共70行模板代码。
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 //第一步,定义AVL树 5 struct Node { 6 int v,height; 7 Node *lchild; 8 Node *rchild; 9 }; 10 //第二步,求以root为根结点的树的高度 11 int getheight(Node* root) { 12 if(root == NULL) return 0; 13 return root->height; 14 } 15 //第三步,更新结点root的height 16 void updateheight(Node* root) { 17 root->height = max(getheight(root->lchild),getheight(root->rchild))+1; 18 } 19 //第四步,求结点root的平衡因子 20 int getbalancefactor(Node* root) { 21 return getheight(root->lchild)-getheight(root->rchild); 22 } 23 //第五步,左旋,引用型指针 24 void L(Node* &root) { 25 Node* temp = root->rchild; 26 root->rchild = temp->lchild; 27 temp->lchild = root; 28 updateheight(root); 29 updateheight(temp); 30 root = temp; 31 } 32 //第六步,右旋 33 void R(Node* &root) { 34 Node* temp = root->lchild; 35 root->lchild = temp->rchild; 36 temp->rchild = root; 37 updateheight(root); 38 updateheight(temp); 39 root = temp; 40 } 41 //第七步,建立AVL树 42 void insert(Node* &root,int v) { 43 if(root == NULL) { 44 root = new Node; 45 root->v = v; 46 root->height = 1; 47 root->lchild = root->rchild = NULL; 48 return ; 49 } 50 if(v < root->v) { 51 insert(root->lchild,v); 52 updateheight(root); 53 if(getbalancefactor(root) == 2) { 54 if(getbalancefactor(root->lchild) == 1)//LL型 55 R(root);//右旋 56 else if(getbalancefactor(root->lchild) == -1) { //LR型 57 L(root->lchild);//左旋 58 R(root);//右旋 59 } 60 } 61 } else { 62 insert(root->rchild,v); 63 updateheight(root); 64 if(getbalancefactor(root) == -2) { 65 if(getbalancefactor(root->rchild) == -1)//RR型 66 L(root);//左旋 67 else if(getbalancefactor(root->rchild) == 1) { //RL型 68 R(root->rchild);//右旋 69 L(root);//左旋 70 } 71 } 72 } 73 } 74 int main() { 75 int n,v; 76 cin>>n; 77 Node* root = NULL; 78 while(n--) { 79 cin>>v; 80 insert(root,v); 81 } 82 cout<<root->v<<endl; 83 return 0; 84 }