Description
给出结点的插入序列,构造AVL Tree。
Input
第一行含一个整数t(0<t<10),为测试样例个数。
每个测试样例包含两行;第1行为一个整数n,表示插入的结点数;第2行依照插入顺序给出n个结点的数值(整数),之间用一个空格分隔。
Output
对每个测试样例单独一行输出对应AVL Tree的前序遍历序列,每输出一个结点的数值(包括最后一个结点),其后输出一个空格。
我写之前借鉴了其他博客和课本上的代码。最终觉得课本上的写法不好,太复杂,转而模仿了其他博客中的写法
#include <iostream>
using namespace std;
struct avlNode {
int data, height;
avlNode* left, *right;
avlNode(const int d, avlNode* l = NULL,
avlNode* r = NULL) : data(d), left(l), right(r) {}
};
int get_height(avlNode* p) {
if (p != NULL) return p->height;
else return 0;
}
inline int max(const int a,const int b) {
return a > b ? a: b;
}
avlNode* left_rotation(avlNode* p) {
avlNode* right_tree = p->right;
p->right = right_tree->left;
right_tree->left = p;
p->height = max(get_height(p->left), get_height(p->right)) +1;
right_tree->height = max(get_height(right_tree->left), get_height(right_tree->left)) +1;
return right_tree;
}
avlNode* right_rotation(avlNode* p) {
avlNode* left_tree = p->left;
p->left = left_tree->right;
left_tree->right = p;
p->height = max(get_height(p->left), get_height(p->right)) + 1;
left_tree->height = max(get_height(left_tree->left), get_height(left_tree->right)) + 1;
return left_tree;
}
avlNode* RL_rotation(avlNode* p) {
p->right = right_rotation(p->right);
return left_rotation(p);
}
avlNode* LR_rotation(avlNode* p) {
p->left = left_rotation(p->left);
return right_rotation(p);
}
void insert(avlNode* &p,int key) {
if (p == NULL) {
p = new avlNode(key);
} else if (key > p->data) {
insert(p->right, key);
if (get_height(p->right) - get_height(p->left) == 2) {
if (key > (p->right)->data) p = left_rotation(p);
else if (key < (p->right)->data) p = RL_rotation(p);
}
} else if (key < p->data) {
insert(p->left, key);
if (get_height(p->left) - get_height(p->right) == 2) {
if (key < (p->left)->data) p = right_rotation(p);
else if (key > (p->left)->data) p = LR_rotation(p);
}
}
p->height = max(get_height(p->left), get_height(p->right)) + 1;
}
void preorder(avlNode* p) {
if (p != NULL) {
cout << p->data + 1 << " ";
preorder(p->left);
preorder(p->right);
}
}
int main() {
int t, n, i, temp;
avlNode* root = NULL;
cin >> t;
while (t--) {
cin >> n;
for (i = 0; i < n; i++) {
insert(root, i);
}
}
preorder(root);
}
本文介绍了一种构造AVL树的方法,并实现了相应的插入和平衡调整操作。通过递归方式完成节点插入,同时利用左旋、右旋等操作保持树的平衡特性。最后展示了如何进行前序遍历。
5549

被折叠的 条评论
为什么被折叠?



