0

What am I doing wrong in the logic of the below code : it is returning just the value of inserted node , not the whole tree. (See Output)

The method of printing the nodes of tree using the root node is predefined.I just have to return the root of the tree here.

 /* Node is defined as :
 class Node 
 int data;
 Node left;
 Node right;

 */

static Node Insert(Node root,int value)
 {       
  if(root == null){
     root = new Node();
     root.data= value ;
     return root;   
  }

 else{
  if(value<root.data)
   return Insert(root.left,value);

 else if(value > root.data)
     return  Insert(root.right,value);

 else return null;    
    }

   }

Input -

   5           //number of nodes

  4 2 3 1 7    // values of nodes

   6           //value of node to be inserted

(Expected)Output :

1 2 3 4 6 7

My output :

 6

1 Answer 1

1

Just modify if condition as:

if(root == null)
{
 root = new Node();
 root.data= value ;
 root.left=null;
 root.right=null;
 return root;
}

And modify the else condition as:

else
{
  if(value<root.data)
   {
     root.left=Insert(root.left,value);
     return root;
   }
  else if(value > root.data)
   {
     root.right= Insert(root.right,value);
     return root;
   }
  else 
   {
     System.out.println("duplicate value"); 
     return root;
   }
}    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.