Pagini recente » Cod sursa (job #1882235) | Cod sursa (job #1871498)
#include<stdio.h>
#include<stdlib.h>
struct Node{
int key;
int height;
int count;
struct Node *left;
struct Node *right;
};
inline int max(int a, int b){
return (a > b) ? a : b;
}
int height(struct Node *N){
if(N == NULL) return 0;
return N -> height;
}
struct Node* newNode(int key){
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node -> key = key;
node -> height = 1;
node -> count = 1;
node -> left = NULL;
node -> right = NULL;
return(node);
}
struct Node *rightRotate(struct Node *y){
struct Node *x = y -> left;
struct Node *T2 = x -> right;
x -> right = y;
y -> left = T2;
y -> height = max(height(y -> left), height(y -> right)) + 1;
x -> height = max(height(x -> left), height(x -> right)) + 1;
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(height(x -> left), height(x -> right)) + 1;
y -> height = max(height(y -> left), height(y -> right)) + 1;
return y;
}
int getBalance(struct Node *N){
if(N == NULL) return 0;
return height(N -> left) - height(N -> right);
}
struct Node* Insert(struct Node* node, int key){
if(node == NULL)
return(newNode(key));
if(key == node->key){
(node -> count)++;
return node;
}
if(key < node -> key)
node -> left = Insert(node -> left, key);
else if(key > node -> key)
node -> right = Insert(node -> right, key);
else return node;
node -> height = 1 + max(height(node -> left), height(node -> right));
int balance = getBalance(node);
if(balance > 1 && key < node -> left -> key) return rightRotate(node);
if(balance < -1 && key > node -> right -> key) return leftRotate(node);
if(balance > 1 && key > node -> left -> key){
node -> left = leftRotate(node -> left);
return rightRotate(node);
}
if(balance < -1 && key < node -> right -> key){
node -> right = rightRotate(node -> right);
return leftRotate(node);
}
return node;
}
void Inorder(struct Node *root){
if(root == NULL) return;
Inorder(root -> left);
printf("%d ", root -> key);
Inorder(root -> right);
}
int main(){
struct Node *root = NULL;
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
int N, x;
scanf("%d", &N);
while(N--){
scanf("%d", &x);
root = Insert(root, x);
}
Inorder(root);
return 0;
}