1066 Root of AVL Tree (25)(25 分)
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120
Sample Output 1:
70
Sample Input 2:
7
88 70 61 96 120 90 65
Sample Output 2:
88
题意:
给出AVL树的插入顺序,要求构建AVL树,并输出根结点的值。
思路:
AVL模板题,原理不赘述。详见《算法笔记》。
需要引起注意的是,若操作会改变结点的地址,则要 引用传值。如insert(),leftRotation(),rightRotation()操作。而updateHeight()操作只是改变了结点的数据域,并未改变结点的地址,所以无需加引用(当然,加引用也没关系)。
代码:
#include#include using namespace std;struct Node{ int val; int height;//以该结点为根结点的子树高度 Node *lchild,*rchild; Node(int v):val(v),height(1),lchild(nullptr),rchild(nullptr){}};int getHeight(Node* pNode){ if(pNode==nullptr) return 0; else return pNode->height;}int getBalancedFactor(Node* pNode){ return getHeight(pNode->lchild)-getHeight(pNode->rchild);}void updateHeight(Node* pNode){ pNode->height=max(getHeight(pNode->lchild),getHeight(pNode->rchild))+1;}void leftRotation(Node* &pNode){ Node* temp=pNode->rchild; pNode->rchild=temp->lchild; temp->lchild=pNode; updateHeight(pNode); updateHeight(temp); pNode=temp;}void rightRotation(Node* &pNode){ Node* temp=pNode->lchild; pNode->lchild=temp->rchild; temp->rchild=pNode; updateHeight(pNode); updateHeight(temp); pNode=temp;}void insert(Node* &root,int val){ if(root==nullptr){ root=new Node(val); return; } if(val < root->val){ insert(root->lchild,val); updateHeight(root); if(getBalancedFactor(root)==2){ if(getBalancedFactor(root->lchild)==1){ //LL型 rightRotation(root); }else if(getBalancedFactor(root->lchild)==-1){ //LR型 leftRotation(root->lchild); rightRotation(root); } } }else{ insert(root->rchild,val); updateHeight(root); if(getBalancedFactor(root)==-2){ if(getBalancedFactor(root->rchild)==-1){ //RR型 leftRotation(root); }else if(getBalancedFactor(root->rchild)==1){ //RL型 rightRotation(root->rchild); leftRotation(root); } } }}int main(){ int n,val; Node* root=nullptr; scanf("%d",&n); for(int i=0;i val); return 0;}