问题 A: 算法9-9~9-12:平衡二叉树的基本操作
- AVL 树的基本操作,套用固定模板即可。参考代码如下。
#include<iostream>
#include<algorithm>
using namespace std;
struct node {
int data;
int height = 1;
node* left = NULL;
node* right = NULL;
};
int getHeight(node* root) {
if (root == NULL) return 0;
return root->height;
}
int getBalanceFactor(node* root) {
return getHeight(root->left) - getHeight(root->right);
}
void updateHeight(node* &root) {
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
}
void L(node* &root) {
node* temp = root->right;
root->right = temp->left;
temp->left = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node* &root) {
node* temp = root->left;
root->left = temp->right;
temp->right = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node* &root, int data) {
if (root == NULL) {
root = new node;
root->data = data;
return;
}
if (data < root->data) {
insert(root->left, data);
updateHeight(root);
if (getBalanceFactor(root) == 2) {
if (getBalanceFactor(root->left) == 1)
R(root);
else if (getBalanceFactor(root->left) == -1) {
L(root->left);
R(root);
}
}
}
else {
insert(root->right, data);
updateHeight(root);
if (getBalanceFactor(root) == -2) {
if (getBalanceFactor(root->right) == -1)
L(root);
else if (getBalanceFactor(root->right) == 1) {
R(root->right);
L(root);
}
}
}
}
bool search(node* root, int v) {
if (root == NULL)
return false;
if (root->data == v)
return true;
else if (root->data > v)
search(root->left, v);
else search(root->right, v);
}
int main() {
int n, k, v;
cin >> n >> k;
node* AVL = NULL;
for (int i = 0; i < n; i++) {
cin >> v;
insert(AVL, v);
}
for (int i = 0; i < k; i++) {
cin >> v;
if (search(AVL, v))
cout << "1 ";
else cout << "0 ";
}
cout << endl;
return 0;
}