Reputation: 1088
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
Upvotes: 0
Views: 4291
Reputation: 8292
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;
}
}
Upvotes: 1