|
题目大意
按照给出的顺序将节点插入一棵二叉树中,使得这棵树成为二叉平衡搜索树。最后输出层序遍历,并判断是否是一棵完全二叉树。思路解析
把AVL树调整代码敲上去就可以了,需要牢记模板。关于AVL树的有关讲解请移步:点击这里
示例代码
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node{
public:
int val;
struct node* left, *right;
};
node* LLRotation(node* k1) {
node* k2 = k1->left;
k1->left = k2->right;
k2->right = k1;
return k2;
}
node* RRRotation(node* k1) {
node* k2 = k1->right;
k1->right = k2->left;
k2->left = k1;
return k2;
}
node* LRRotation(node* k1) {
k1->left = RRRotation(k1->left);
node* k3 = LLRotation(k1);
return k3;
}
node* RLRotation(node* k1) {
k1->right = LLRotation(k1->right);
node* k2 = RRRotation(k1);
return k2;
}
int getHeight(node* nod) {
if (nod == NULL) return 0;
return max(getHeight(nod->left), getHeight(nod->right)) + 1;//注意+1
}
node* insert(node* root,int val) {
if (root == NULL) {
root = new node();
root->val = val;
return root;
}
if ( val < root->val) {
root->left = insert(root->left, val);
if (getHeight(root->left) - getHeight(root->right) == 2) {//左子树失衡
if (val < root->left->val)
root = LLRotation(root);
else
root = LRRotation(root);
}
}
else {
root->right = insert(root->right, val);
if (getHeight(root->left) - getHeight(root->right) == -2) {
if (val < root->right->val)
root = RLRotation(root);
else
root = RRRotation(root);
}
}
return root;
}
vector<vector<int>> res(20);
vector<int> com;
int maxdeep = 0;
void level(node* root, int deep, int count) {
if (root == NULL) return;
res[deep].push_back(root->val);
com.push_back(count);
if (deep > maxdeep) maxdeep = deep;
level(root->left, deep + 1, 2 * count + 1);
level(root->right, deep + 1, 2 * count + 2);
}
int main() {
int n,val;
scanf("%d", &n);
node* root = NULL;
for (int i = 0; i < n; i++) {
scanf("%d", &val);
root = insert(root, val);
}
level(root, 0, 0);
for (int i = 0; i <= maxdeep; i++) {
for (int j = 0; j < res[i].size(); j++) {
if (i == 0 && j == 0)
printf("%d", res[i][j]);
else
printf(" %d", res[i][j]);
}
}
printf("\n");
sort(com.begin(), com.end());
int i;
for (i = 0; i < n && com[i] == i; i++);
if (i == n)
printf("YES\n");
else
printf("NO\n");
return 0;
}