Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node {
- int data;
- node* left, * right;
- unsigned char height;
- node(char in) { data = in; left = right = NULL; height = 1; }
- };
- void Print(node* Tree, int l) {
- int i;
- if (Tree != NULL) {
- Print((*Tree).right, l + 1);
- for (i = 1; i <= l; i++) cout << " "; {
- cout << Tree->data << endl;
- }
- Print(((*Tree).left), l + 1);
- }
- }
- void print(node* t, int u) {
- //cout << "PRINT!\n";
- if (t == NULL) {
- //`cout << "T = NULL!\n";
- return;
- }
- else {
- print(t->left, u++);
- for (int i = 0; i < u; i++) cout << "|";
- cout << t->data << endl;
- u--;
- };
- print(t->right, u++);
- }
- unsigned char height(node* t) {
- if (t) {
- return t->height;
- }
- else {
- return 0;
- }
- }
- void fixheight(node* p) {
- unsigned char hl = height(p->left);
- unsigned char hr = height(p->right);
- if (hl > hr) p->height=hl+1;
- else p->height=hr+1;
- }
- int bf(node* p) {
- return height(p->right) - height(p->left);
- }
- node* rotateright(node* p) {
- node* q = p->left;
- p->left = q->right;
- q->right = p;
- fixheight(p);
- fixheight(q);
- return q;
- }
- node* rotateleft(node* q) {
- node* p = q->right;
- q->right = p->left;
- p->left = q;
- fixheight(q);
- fixheight(p);
- return p;
- }
- node* balance(node* p) {
- cout << "BALANCE!\n";
- fixheight(p);
- if (bf(p) == 2) {
- if (bf(p->right) < 0) p->right = rotateright(p->right);
- return rotateleft(p);
- }
- if (bf(p) == -2) {
- if (bf(p->left) > 0) p->left = rotateleft(p->left);
- return rotateright(p);
- }
- return p;
- }
- node* push(unsigned char in, node** t) {
- if ((*t) == NULL) {
- cout << "PUSH! "; (*t) = new node(in); cout << (*t)->data << endl; return balance((*t));
- }
- if (in < (*t)->data) { (*t)->left = push(in, &(*t)->left); }
- else (*t)->right = push(in, &(*t)->right);
- return balance((*t));
- }
- int main() {
- node* tree = NULL;
- push(13, &tree);
- push(8, &tree);
- push(17, &tree);
- push(1, &tree);
- push(11, &tree);
- push(15, &tree);
- push(25, &tree);
- push(22, &tree);
- push(27, &tree);
- print(tree, 0);
- Print(tree, 0);
- return 0;
- }
Add Comment
Please, Sign In to add comment