Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /*AVL self-balancing trees: Insertion of a node
  2. - This took me so much time, so I had to post this.
  3. */
  4.  
  5. /* Assumption:
  6. 1. Null node have a height of -1
  7. 2. Leaf node have a height of 0
  8. */
  9.  
  10. /* Node is defined as :
  11. typedef struct node
  12. {
  13. int val;
  14. struct node* left;
  15. struct node* right;
  16. int ht;
  17. } node;
  18. */
  19.  
  20. int getHeight(node* n){
  21. if(n==NULL) return -1;
  22. return n->ht;
  23. }
  24.  
  25. int getBalance(node* r){
  26. if(r==NULL) return -1;
  27. return getHeight(r->left) - getHeight(r->right);
  28. }
  29.  
  30. node* leftRotate(node* n){
  31. node* right = n->right;
  32. node* tree = right->left;
  33.  
  34. // rotation
  35. right->left = n;
  36. n->right = tree;
  37.  
  38. // height update
  39. n->ht = max(getHeight(n->left), getHeight(n->right)) + 1;
  40. right->ht = max(getHeight(right->left), getHeight(right->right)) + 1;
  41.  
  42. return right;
  43. }
  44.  
  45. node* rightRotate(node* n){
  46. node* left = n->left;
  47. node* tree = left->right;
  48.  
  49. // rotation
  50. left->right = n;
  51. n->left = tree;
  52.  
  53. // height updates
  54. n->ht = max(getHeight(n->left), getHeight(n->right)) + 1;
  55. left->ht = max(getHeight(left->left), getHeight(left->right)) + 1;
  56.  
  57. return left;
  58. }
  59.  
  60. node* insert(node * root, int val){
  61. // insertion at leaf
  62. if(root == NULL){node* n = new node(); n->val = val; n->ht = 0; return n;}
  63.  
  64. if(val< root->val){
  65. root->left = insert(root->left, val);
  66. }else if(val > root->val){
  67. root->right = insert(root->right, val);
  68. }else{
  69. // this case not allowed in AVL-trees (no duplicates)
  70. return root;
  71. }
  72.  
  73. root->ht = 1 + max(getHeight(root->left), getHeight(root->right));
  74. int bal = getBalance(root);
  75.  
  76. // Cases
  77. // left left case
  78. if(bal > 1 && val < root->left->val){
  79. return rightRotate(root);
  80. }
  81. // right right case
  82. if(bal < -1 && val > root->right->val){
  83. return leftRotate(root);
  84. }
  85. // left right case
  86. if(bal > 1 && val > root->left->val){
  87. root->left = leftRotate(root->left);
  88. return rightRotate(root);
  89. }
  90. //right left case
  91. if(bal < -1 && val < root->right->val){
  92. root->right = rightRotate(root->right);
  93. return leftRotate(root);
  94. }
  95. return root;
  96. }
  97.  
  98. /* It works for me. If it doesn't work for you: Drop me a mail by raising an issue: ankit03june AT gmail DOT com*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement