Hell can you help me on this,how can i insert a new node in the binary tree and to keep track the current node
example:
input number: 50
Succesfully inserted!
input number:40
this will print "inserted at the left of 50"
input numbr: 80
this will print "inserted at the right of 50"
input number: 20
this should print "inserted at the left of 40"
and etc.....
that is my problem how can i get track of the current node so that i can insert the new node,my code is always display the right of 50 or left of 50 it should follow th BST rule.....can you help me please thank you in advance hoping for your positive responds...
here is my code....
class Node
{
public int num;
public Node llink;
public Node rlink;
}
public class BinaryTreeOperations
{
private Node current;
private Node root;
private Node temp;
public boolean isEmpty()
{
return root==null;
}
public void insertNum(int n)
{
Node temp=null;
Node current =null;
Node newNode = new Node();
newNode.num=n;
newNode.llink=null;
newNode.rlink=null;
if(isEmpty())
{
root=newNode;
System.out.println("Successfully inserted!");
}
else
{
temp=root;
while(temp!=null)
{
newNode = temp;
current = newNode;
temp =null;
}
if(n<current.num)
{
newNode.llink=newNode;
current= newNode.llink;
System.out.println("inserted on the left subtree ");
}
else
{
newNode.rlink=newNode;
current = newNode.rlink;
System.out.println("inserted on the right subtree ");
}
}
}
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
BinaryTreeOperations bt = new BinaryTreeOperations();
do{
System.out.print("Insert a number: ");
bt.insertNum(console.nextInt());
}
while(select!=5);
}
}