题目描述
1066 Root of AVL Tree (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.
(……)
测试要点
-
我个人是分不清左右的,所以对我来说最重要的是测试左右旋函数L、R。测出一个是对的另一个镜像即可
3 1 2 3
-
特殊点:只有一个节点的时候
-
测完我的代码就通过了,这里多提供一组测试样例,正确答案是88
12 88 70 61 96 120 88 70 61 96 120 90 65
代码如下:
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#define MAX 100
using namespace std;
int n;
int data[MAX];
struct Node{
Node *left, *right;
int data;
int h;
};
int getHeight(Node* root) {
if(root== nullptr) {
return 0;
}
return root->h;
}
void updateHeight(Node* &root) {
if(root->left== nullptr && root->right== nullptr) {
root->h=1;
} else {
root->h= max(getHeight(root->left), getHeight(root->right))+1;
}
}
int getBalanceFactor(Node* root) {
return getHeight(root->left)- getHeight(root->right);
}
void R(Node* &root) {
Node* tmp = root->left;
root->left = tmp->right;
tmp->right=root;
updateHeight(root);
updateHeight(tmp);
root=tmp;
}
void L(Node* &root) {
Node* tmp = root->right;
root->right = tmp->left;
tmp->left=root;
updateHeight(root);
updateHeight(tmp);
root=tmp;
}
Node* newNode(int data) {
Node* node=new Node;
node->left=node->right= nullptr;
node->data=data;
node->h=1;
return node;
}
void insert(Node* &root, int data) {
if(root==nullptr) {
root = newNode(data);
// root->data=data;
// updateHeight(root); // root->h=1;
return;
}
if(data<root->data) {
insert(root->left, data);
updateHeight(root);
if(getBalanceFactor(root)==2) {
if(getBalanceFactor(root->left)>0) {
R(root);
} else {
L(root->left);
R(root);
}
}
} else {
insert(root->right, data);
updateHeight(root);
if(getBalanceFactor(root)==-2) {
if(getBalanceFactor(root->right)>0) {
R(root->right);
L(root);
} else {
L(root);
}
}
}
}
Node* create(int data[], int n) {
Node* root= nullptr;
for(int i=0; i<n; i++) {
insert(root, data[i]);
}
return root;
}
int main() {
fstream fin;
fin.open("tmp4.txt");
fin>>n;
for(int i=0;i<n;i++) {
fin>>data[i];
}
// cin>>n;
// for(int i=0;i<n;i++) {
// cin>>data[i];
// }
Node* root= create(data, n);
cout<<root->data;
}