Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Node *left;
- Node *right;
- Node *parent;
- int height; // add this one
- int max(int a, int b)
- {
- return (a > b)? a : b;
- }
- Node * minValueNode(Node* node)
- {
- Node* current = node;
- while (current->left != NULL)
- current = current->left;
- return current;
- }
- int getBalance(Node *N)
- {
- if (N == NULL)
- return 0;
- return height(N->left) - height(N->right);
- }
- Node *leftRotate(Node *x)
- {
- Node *y = x->right;
- 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;
- }
- Node *rightRotate(Node *y)
- {
- Node *x = y->left;
- 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;
- }
- Node* deleteNodes(Node* root, int key)
- {
- if (root == NULL)
- return root;
- if ( key < root->key )
- root->left = deleteNodes(root->left, key);
- else if( key > root->key )
- root->right = deleteNodes(root->right, key);
- else
- {
- if( (root->left == NULL) ||
- (root->right == NULL) )
- {
- Node *temp = root->left ? root->left : root->right;
- if (temp == NULL)
- {
- temp = root;
- root = NULL;
- }
- else
- *root = *temp;
- free(temp);
- }
- else
- {
- Node* temp = minValueNode(root->right);
- root->key = temp->key;
- root->right = deleteNodes(root->right, temp->key);
- }
- }
- if (root == NULL)
- return root;
- root->height = 1 + max(height(root->left), height(root->right));
- int balance = getBalance(root);
- if (balance > 1 && getBalance(root->left) >= 0)
- return rightRotate(root);
- if (balance > 1 && getBalance(root->left) < 0)
- {
- root->left = leftRotate(root->left);
- return rightRotate(root);
- }
- if (balance < -1 && getBalance(root->right) <= 0)
- return leftRotate(root);
- if (balance < -1 && getBalance(root->right) > 0)
- {
- root->right = rightRotate(root->right);
- return leftRotate(root);
- }
- return root;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement