PAT1066 Root of AVL Tree-平衡二叉树构建
题目链接:
PAT1066 Root of AVL Tree
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
总体思路:
分为左左,左右,右左,右右四种情况进行调整。
#include <iostream>
#include<cstdio>
using namespace std;
struct node{
int v;
node *left,*right;
};
int getDepth(node *root){
if(root==NULL)
return 0;
int dep1=getDepth(root->left);
int dep2=getDepth(root->right);
int dep=max(dep1,dep2)+1;
return dep;
}
node *LL(node *k1){
node *k2=k1->left;
k1->left=k2->right;
k2->right=k1;
return k2;
}
node *RR(node *k1){
node *k2=k1->right;
k1->right=k2->left;
k2->left=k1;
return k2;
}
node *LR(node *k1){//先RR再LL
k1->left=RR(k1->left);
return LL(k1);
}
node *RL(node *k1){
k1->right=LL(k1->right);
return RR(k1);
}
node *build(node *root,int v){
if(root==NULL){
root=new node();
root->v=v;
root->left=root->right=NULL;
return root;
}else{
if(v>=root->v){
root->right=build(root->right,v);
if(getDepth(root->right)-getDepth(root->left)==2){
if(v>=root->right->v)
root=RR(root);
else
root=RL(root);
}
return root;
}else{
root->left=build(root->left,v);
if(getDepth(root->left)-getDepth(root->right)==2){
if(v<root->left->v)
root=LL(root);
else
root=LR(root);
}
return root;
}
}
}
int main(int argc, char** argv) {
int n;scanf("%d",&n);
node *root=NULL;
for(int i=0;i<n;i++){
int x;scanf("%d",&x);
root=build(root,x);
}
printf("%d",root->v);
return 0;
}