Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, May 11, 2017

Insert Node in Tree



static Node Insert(Node root,int value)
    {
      if(root==null)
                  {
          Node temp=new Node();
    temp.data=value;
    temp.left=null;
    temp.right=null;
          root=temp;
}
        else if(value<root.data)
                root.left= Insert(root.left,value);
       
        else if(value>root.data)
                 root.right=Insert(root.right,value);
       
    return root;
     
    }


Explanation;


Check till we are at the last node then at leaf node we will insert at left/right depending upon value.

0 Comments:

Post a Comment

Stats