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

Powered by Blogger.

Monday, September 11, 2017

Insert Node in BST


Explanation :

check if node is empty then create a new node and return;
if data is already there return 
else check with lesser and greater than element and recur.

Code:

 Node insert(Node root, int data)
    {
         if(root==null)
         return new Node(data);
          if(root.data==data)
                return root;
         if(data<root.data)
          root.left=insert(root.left,data);
         else
          root.right=insert(root.right,data);
          return root;
    }

0 Comments:

Post a Comment

Stats