Advertisement
adnan_dipta89

AVLTree Insert

Oct 17th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1.  
  2. /* Node is defined as :
  3. typedef struct node
  4. {
  5.     int val;
  6.     struct node* left;
  7.     struct node* right;
  8.     int ht;
  9. } node; */
  10.  
  11. node* newNode(int val)
  12. {
  13.     node* n = new node;
  14.     n->val = val;
  15.     n->left = NULL;
  16.     n->right = NULL;
  17.     n->ht = 0;
  18.     return n;
  19. }
  20. int height(node *root)
  21. {
  22.     if(root==NULL)
  23.         return -1;
  24.     return root->ht;
  25. }
  26. int getBalance(node* root)
  27. {
  28.     if(root==NULL)
  29.         return 0;
  30.     int l = height(root->left);
  31.     int r = height(root->right);
  32.     //cout << root->val << " " << l << " " << r << endl;
  33.     return l-r;
  34. }
  35. node* leftRotate(node* x)
  36. {
  37.     node* y = x->right;
  38.     node* T2 = y->left;
  39.    
  40.     y->left = x;
  41.     x->right = T2;
  42.    
  43.     x->ht = 1+max(height(x->left),height(x->right));
  44.     y->ht = 1+max(height(y->left),height(y->right));
  45.    
  46.     return y;
  47. }
  48. node* rightRotate(node* y)
  49. {
  50.     node* x = y->left;
  51.     node* T2 = x->right;
  52.    
  53.     x->right = y;
  54.     y->left = T2;
  55.    
  56.     y->ht = 1+max(height(y->left),height(y->right));
  57.     x->ht = 1+max(height(x->left),height(x->right));
  58.    
  59.     return x;
  60. }
  61. node * insert(node * root,int val)
  62. {
  63.     if(root == NULL)
  64.     {
  65.         return newNode(val);
  66.     }
  67.     if(val < root->val)
  68.     {
  69.         root->left = insert(root->left,val);
  70.     }
  71.     else if(val > root->val)
  72.     {
  73.         root->right = insert(root->right,val);
  74.     }
  75.     else
  76.         return root;
  77.     root->ht = 1+max(height(root->left),height(root->right));
  78.     int balance = getBalance(root);
  79.     if(balance > 1  && val < root->left->val)
  80.     {
  81.         return rightRotate(root);
  82.     }
  83.     else if(balance < -1 && val > root->right->val)
  84.     {
  85.         return leftRotate(root);
  86.     }
  87.     else if(balance > 1 && val > root->left->val)
  88.     {
  89.         root->left = leftRotate(root->left);
  90.         return rightRotate(root);
  91.     }
  92.     else if(balance < -1 && val < root->right->val)
  93.     {
  94.         root->right = rightRotate(root->right);
  95.         return leftRotate(root);
  96.     }
  97.     return root;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement