java - Problem in binary tree; need help -


can me please? making binary tree node insertion. how can insert new node current node in respect of bst rule?

example: first root empty.

input number: 50

this display "success!"

insert number: 40

successfully inserted in left subtree of 50

insert number: 20

successfully inserted in left subtree of 40

insert number: 80

successfully inserted in right subtree of 50

can me please? thank in advance hoping positive response...

here's code:

class node {   public int num;   public node llink;   public node rlink; }   public class binarytreeoperations {   //public node llink=null;   // public node rlink=null;   private node temp;   private node current;   private node root;    public boolean isempty()   {     return root==null;   }     public void insertnum(int n)   {      temp=null;     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)       {         current = temp;         root = current;         temp=null;        }      if(n<current.num)     {       current.llink=newnode;       //current.llink=temp;       system.out.println("inserted on left subtree " +current.num);     }       else     {       newnode.rlink=newnode;        system.out.println("inserted on right subtree  "+current.num );     }     } }  

your while loop seems wrong. want start @ root , traverse tree until reach node serve parent of new node. below not doing traversal or inspection find new node should go. need doing.

while(temp!=null) {     current = temp;     root = current;     temp=null;  } 

should this:

while(parent not found) {     if (new node smaller current) {         if (current has left child) {             assign left child current , loop         } else {             make current parent of new node         }     } else {         ....     } } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

sql server - python to mssql encoding problem -

windows - Python Service Installation - "Could not find PythonClass entry" -