recursion - Java Binary tree insert is not working properly -
when add node example, named "bob" in insert method:
public void insert(string alabel){ //left recursion: if(this.getlabel().compareto(alabel) <= 0) { if (childrenleft == null) { bstreenode anode = new bstreenode(alabel,this); return; } else { childrenleft.insert(alabel); } } //right recursion else { if (childrenright==null) { bstreenode anode = new bstreenode(alabel,this); return; } else{ childrenright.insert(alabel); } } }
my tree adds blank node no label on left side of treee only. there wrong (bstreenode anode = new bstreenode;)? because when hard code nodes like:
bstreenode louis = new bstreenode("louis", treeroot); bstreenode bonny = new bstreenode( "bonny", treeroot); bstreenode sue = new bstreenode("anne", bonny); bstreenode sam = new bstreenode("sam",louis); bstreenode anne2 = new bstreenode( "delta", bonny); bstreenode frank = new bstreenode("kalle", louis);
the tree shows both label , inserted @ desired location. other code- constructor:
public bstreenode( string alabel,bstreenode aparent){ label = alabel; parent = aparent; //add node child of node's parent either left or right if(parent != null){ if(parent.getlabel().compareto(label)<= 0) { parent.addleftchild(this); } if(parent.getlabel().compareto(label)> 0) { parent.addrightchild(this); } } }
this constructor adds node parent when node created. add childleft , right methods:
private void addleftchild(bstreenode anode){ if(childrenleft == null) this.childrenleft = anode; } private void addrightchild(bstreenode anode) { if(childrenright == null) this.childrenright = anode; }
most binary trees follow different style, , set parent's left/right child inside recursive method, instead of child going , telling it's new parent
this code bit more standard how binary trees function:
public void insert(string alabel) { if(getlabel().compareto(alabel) <= 0) if(childrenleft == null) childrenleft = new bstreenode(alabel, this); else childrenleft.insert(alabel); else if(childrenright == null) childrenright = new bstreenode(alabel, this); else childrenright.insert(alabel); }
that code should correctly save values of bstreenodes being created, , has added effect of being less confusing how parent getting it's child
it makes whole lot more sense people parent getting child, instead of child reaching node , telling it's new child on block
Comments
Post a Comment