AVL Tree Insertion | Practice | GeeksforGeeks

Given a AVL tree and N values to be inserted in the tree. Write a function to insert a given value into the tree.
Example 1:
â€‹N = 3
Values to be inserted = {5,1,4}

Input:      
Value to be inserted = 5
Output:
    5

Input :      
Value to be inserted = 1
Output:
    5
   /
  1

â€‹Input :      
Value to be inserted = 4
Output:
    4
   / \
  1   5

Your Task:  
You dont need to read input or print anything. Complete the function insertToAVL() which takes the root of the tree and the value of the node to be inserted as input parameters and returns the root of the modified tree.
Note:
The tree will be checked after each insertion. 
If it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment.
If instead all insertions are successful, inorder traversal of tree will be printed.

Expected Time Complexity: O(log N)
Expected Auxiliary Space: O(height of tree)

Constraints:
1 ≤ N ≤ 500
0
gyaanutsukin 29 minutes
class Solution {
    static int height(Node root) {
        if (root == null) {
            return 0;
        }
        return root.height;
    }
    
    static int calculateBalanceFactor(Node root) {
        if (root == null) {
            return 0;
        }
        
        return height(root.left) - height(root.right);
    }
    
    Node rotateRight(Node x) {
        if (x == null) {
            return x;
        }
        
        Node y = x.left;
        Node yR = y.right;
        
        // Perform rotation
        x.left = yR;
        y.right = x;
        
        // Update heights --> order of height updation is important
        x.height = 1 + Math.max(height(x.left), height(x.right));
        y.height = 1 + Math.max(height(y.left), height(y.right));
        
        return y;
    }
    
    Node rotateLeft(Node x) {
        if (x == null) {
            return x;
        }
        
        Node y = x.right;
        Node yL = y.left;
        
        // Perform Rotation
        x.right = yL;
        y.left = x;
        
        // Update heights
        x.height = 1 + Math.max(height(x.left), height(x.right));
        y.height = 1 + Math.max(height(y.left), height(y.right));
        
        return y;
    }
    
    
    public  Node insertToAVL(Node root, int data) {
        /* I. Apply Normal BST Insertion */
        
        // Base Case
        if (root == null) {
            return new Node(data);
        }
        
        if (data < root.data) {
            root.left = insertToAVL(root.left, data);
        } else if (data > root.data) {
            root.right = insertToAVL(root.right, data);
        } else { // data == root.data => duplicates are nt allowed
            return root;
        }
        
        /* II. Update current node's height */
        root.height = 1 + Math.max(height(root.left), height(root.right));
        
        /* III. Calculate the Balance Factor of the current node */
        int balance = calculateBalanceFactor(root);
        
        /* IV. Check for cases of rotation */
        
        // Left Imbalance
        if (balance > 1) {
            // Right GrandChild is Greater --> Left Right Imbalance
            if (data > root.left.data) {
                root.left = rotateLeft(root.left);
            }
            // Common step for both LL and LR
            return rotateRight(root);
        }
        
        // Right Imbalance
        if (balance < -1) {
            // Left Grandhild is Lesser --> Right Left Imbalance
            if (data < root.right.data) {
                root.right = rotateRight(root.right);
            }
            // Common step for both RR and RL
            return rotateLeft(root);
        }
        
        return root;
    }
}
0
patildhiren442 months ago
// Java - 0.8
int height(Node node){
        if(node == null){
            return 0;
        }
        
        return node.height;
    }
    
    int getbalance(Node node){
        if(node==null){
            return 0;
        }
        
        return height(node.left) - height(node.right);
    }
    
    Node rightRo(Node node){
        Node x = node.left;
        Node y = x.right;
        
        x.right = node;
        node.left = y;
       
        node.height = 1 + Math.max(height(node.left), height(node.right));
        x.height = 1 + Math.max(height(x.left), height(x.right));
        
        return x;
    }
    
    Node leftRo(Node node){
        Node x = node.right;
        Node y = x.left;
        
        x.left = node;
        node.right = y;
        
        node.height = 1 + Math.max(height(node.left), height(node.right));
        x.height = 1 + Math.max(height(x.left), height(x.right));
        
        return x;
    }
    
    public  Node insertToAVL(Node node,int data)
    {
        //code here
        if(node==null){
            return new Node(data);
        }
        
        if(data < node.data){
            node.left = insertToAVL(node.left, data);
        }else if(data > node.data){
            node.right = insertToAVL(node.right, data);
        }else{
            return node;
        }
        
        node.height = 1 + Math.max(height(node.left), height(node.right));
        
        int bal = getbalance(node);
        
        if(bal > 1 && data < node.left.data){
            return rightRo(node);
        }
        
        if(bal < -1 && data > node.right.data){
            return leftRo(node);
        }
        
        if(bal > 1 && data > node.left.data){
            node.left = leftRo(node.left); 
            return rightRo(node);
        }
        
        if(bal < -1 && data < node.right.data){
            node.right = rightRo(node.right); 
            return leftRo(node);
        }
        
        return node;
    }
0
lindan1232 months ago
int height(Node *N)
    {
        if (N == NULL)
            return 0;
        return N->height;
    }

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 *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;
}

int getBalance(Node *N)
{
    if (N == NULL)
        return 0;
    return height(N->left) - height(N->right);
}

    Node* insertToAVL(Node* node, int key)
    {
       if (node == NULL)
        return(new Node(key));
 
    if (key < node->data)
        node->left = insertToAVL(node->left, key);
    else if (key > node->data)
        node->right = insertToAVL(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->data)
        return rightRotate(node);
 
    if (balance < -1 && key > node->right->data)
        return leftRotate(node);
 
    if (balance > 1 && key > node->left->data)
    {
        node->left = leftRotate(node->left);
        return rightRotate(node);
    }
 
    if (balance < -1 && key < node->right->data)
    {
        node->right = rightRotate(node->right);
        return leftRotate(node);
    }
 
    return node;
    }
Time Taken : 0.1sec
Cpp
+1
ghoshghoshbishal2 months ago
If you are thinking your code is right but getting the wrong answer, that you don't know why, then there may be a possibility that you are making a mistake in calculating the height inside the rotateLeft() or rotateRight() function. You first need to calculate the height of the bottom node, then calculate the height of the upper node. Let say in rotateRight(), after performing the rotation, you want to return node y, and x is the right node of y, then calculate height of node x first then calculate height of node y. 
0
ajeetkumarece222 months ago
 int height(Node *root){
    if(root==NULL) return 0;
    else
    return root->height;
}
int getBalance_factor(Node *root){
    if(root==NULL) return 0;
    else
      return height(root->left)-height(root->right);
}
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 *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* insertToAVL(Node* root, int key)
    {
        //Your code here
      if(root==NULL) return new Node(key);
    else if(key < root->data){
        root->left=insertToAVL(root->left,key);
    }
    else if(key > root->data){
        root->right=insertToAVL(root->right,key);
    }
    else return root;
    //update the height of this Node
    root->height=max(height(root->left),height(root->right))+1;
    //get balance factor of this Node
    int balance=getBalance_factor(root);
    //now check Node is balanced or not then do rotation
    //for right right case
    if(balance < -1 && key > root->right->data){
        return leftRotate(root);
    }
    //for left left case
    if(balance > 1 && key < root->left->data){
        return rightRotate(root);
    }
    //right left case
    if(balance < -1 && key < root->right->data){
        root->right=rightRotate(root->right);
        return leftRotate(root);
    }
    //left right case
    if(balance > 1 && key > root->left->data){
        root->left=leftRotate(root->left);
        return rightRotate(root);
    }
    return root;
    }
-1
tf1536 months ago
class Solution{
    int height(Node *node){
        if(!node)
            return 0;
        return max(height(node->left),height(node->right))+1;
    }
    int BF(Node *node){
        if(!node)
            return -1;
        else
            return height(node->left)-height(node->right);
    }
    Node *lr(Node *node){
        Node *parent=node->left;
        Node *temp=parent->right;
        parent->right=node;
        node->left=temp;
        return parent;
    }
    Node *rr(Node *node){
        Node *parent=node->right;
        Node *temp=parent->left;
        parent->left=node;
        node->right=temp;
        return parent;
    }
  public:
    Node* insertToAVL(Node* node, int data)
    {
        if(!node)
            return new Node(data);
            
        if(node->data<data)
            node->right= insertToAVL(node->right,data);
        else if(node->data>data)
            node->left=insertToAVL(node->left,data);
        else
            return node;
        
        int bf=BF(node);
        if(bf>1 and data<node->left->data){
            return lr(node);
        }
        if(bf<-1 and data>node->right->data){
            return rr(node);
        }
        if(bf>1 and data>node->left->data){
            node->left=rr(node->left);
            return lr(node);
        }
        if(bf<-1 and data<node->right->data){
            node->right=lr(node->right);
            return rr(node);
        }
        return node;
    }
};
+1
thejiteshkumar7 months ago
Steps: 
find heightget balanced factor(bf)implement right and left rotateUse normal BST insertion with extra conditions use bf value and given data/key value forleft leftright rightleft rightright leftreturn root
find height
get balanced factor(bf)
implement right and left rotate
Use normal BST insertion with extra conditions 
use bf value and given data/key value for
left left
right right
left right
right left
return root
Link to solution (only the above steps and code for class solution is given:
https://ide.geeksforgeeks.org/GeqlbCMrSx
0
thejiteshkumar
This comment was deleted.
+1
Apoorv Singh8 months ago
Apoorv Singh
I don't know why but the code is working correct on my local environment but here it is inserting only first three nodes in the tree. How to resolve this?
0
Y0U Cha*ngE9 months ago
Y0U Cha*ngE
What's wrong in this code// LL means Left imbalance's rotation// LR means Left-right imbalance's rotation// RR means Right imbalance's rotation// RL means Right-left imbalance's rotation
 int findheight(Node *root)    {        if(root==NULL)        return 0;        return  (1+ max(findheight(root->left),findheight(root->right)));    }    void updateheight(Node *root)    {        if(root==NULL)        return;        root->height= findheight(root);    }    int balancefactor(Node *root)    {        if(root==NULL)        return 0;        else          return (((root->left)->height) - ((root->right)->height));    }    /*You are required to complete this method */    Node* LL(Node* root)    {        Node *l=root->left;        Node*lr=l->right;        l->right=root;        root->left=lr;        return l;    }    Node* RR(Node* root)    {        Node *r=root->right;        Node* rl=r->left;        r->left=root;        root->right=rl;        return r;
    }    Node* LR(Node *root)    {        Node *l=root->left, *lr=l->right;        Node *lrl=lr->left, *lrr=lr->right;        lr->right=root;        root->left=lrr;        lr->left=l;        l->right=lrl;        return lr;    }    Node* RL(Node *root)    {        Node *r=root->right, *rl=r->left;        Node *rll=rl->left, *rlr=rl->right;        rl->left=root;        root->right=rll;        rl->right=r;        r->left=rlr;        return rl;    }    Node* insertToAVL(Node* node, int data)    {        if(node==NULL)        {        Node *root=new Node(data);        root->height=1;        return root;        }        if(data > node->data)        node->right=insertToAVL(node->right,data);        else if(data< node->data)        node->left= insertToAVL(node->left,data);        else return node;
        updateheight(node);        int bl=balancefactor(node);
        if( abs(bl) <=1)        return node;        else        {            if((bl==2) && data<node->left->data)            return LL(node);            else if((bl==2) && data> node->left->data)            return LR(node);            else if((bl==-2) && data>node->right->data)            return RR(node);            else if(bl==-2 && data <node->right->data)            return RL(node);        }
    }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.