java - Changing the recursive insertion of the (binary Search tree) to non-recursive? -


i trying change recursive insert method of bst non-recursive( maybe while loop) reason changing because want see if possible.

here code of insertion:

public void insert(string value) {     //the node stored in root     root = insert(value,root); }   private character insert(string value,character current) {        if(current == null)     {         //add root if tree empty       current = new character(value);     }     else         //if value want insert < root value, keep going left till          //it's empty inserted @ left end. done recursion          if(value.compareto(current.getelement())<=-1)         {             current.setleft(insert(value,current.getleft()));         }         else             //if value want insert > root value, keep going right till              //it's empty inserted @ right end. done recursion              if(value.compareto(current.getelement())>=1)             {                 current.setright(insert(value,current.getright()));             }             else             {                 //else, number want insert in in tree                 system.out.println("duplicate numbers inserted" + current.getelement());             }     //returning node tree store in root      return current; } 

could change code non recursive ?

cheers

yes, need alter data structure little bit make works. node has know left child , right child.

the algorithm looks this:

current = root; while(current != null){    if(value.compareto(current.getelement())<=-1)    {         current = current.left_child;    }else if(value.compareto(current.getelement())>=1){         current = current.right_child;    }else{         // duplication    } } 

actually there examples before, may want check out first:


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -