dsf
unknown
abap
3 years ago
2.2 kB
8
Indexable
#include <iostream>
using namespace std;
struct node {
int key;
struct node* left;
struct node* right;
int height;
};
int getheight(struct node* n) {
if (n == NULL)
return 0;
return n->height;
}
struct node* createnode(int key) {
struct node* node = new struct node;
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return node;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
int getbalancefactor(struct node* n) {
if (n == NULL) {
return 0;
}
return getheight(n->left) - getheight(n->right);
}
struct node* rightrotate(struct node* y) {
struct node* x = y->left;
struct node* T2 = x->right;
x->right = y;
y->left = T2;
x->height = max(getheight(x->right), getheight(x->left));
y->height = max(getheight(y->right), getheight(y->left));
return x;
}
struct node* leftrotate(struct node* x) {
struct node* y = x->right;
struct node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(getheight(x->right), getheight(x->left));
y->height = max(getheight(y->right), getheight(y->left));
return y;
}
struct node* insert(struct node* node, int key) {
if (node == NULL)
return createnode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
node->height = 1 + max(getheight(node->left), getheight(node->right));
int bf = getbalancefactor(node);
if (bf > 1 && key < node->left->key) {
return rightrotate(node);
}
if (bf < -1 && key > node->right->key) {
return leftrotate(node);
}
return node;
}
void inorder(struct node* root) {
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
int main() {
struct node* root = NULL;
root = insert(root, 32);
root = insert(root, 4);
root = insert(root, 34);
root = insert(root, 2);
root = insert(root, 30);
root = insert(root, 8);
inorder(root);
return 0;
}
Editor is loading...