java - Recursive Binary Search Tree Insert -
so first java program, i've done c++ few years. wrote think should work, in fact not. had stipulation of having write method call:
tree.insertnode(value);
where value int. wanted write recursively, obvious reasons, had work around:
public void insertnode(int key) { node temp = new node(key); if(root == null) root = temp; else insertnode(temp); } public void insertnode(node temp) { if(root == null) root = temp; else if(temp.getkey() <= root.getkey()) insertnode(root.getleft()); else insertnode(root.getright()); }
thanks advice.
// in java little trickier objects passed copy. // pf reply below. // public calling method public void insertnode(int key) { root = insertnode(root, new node(key)); } // private recursive phone call private node insertnode(node currentparent, node newnode) { if (currentparent == null) { homecoming newnode; } else if (newnode.key > currentparent.key) { currentparent.right = insertnode(currentparent.right, newnode); } else if (newnode.key < currentparent.key) { currentparent.left = insertnode(currentparent.left, newnode); } homecoming currentparent; }
sameer sukumaran
java binary-search-tree
No comments:
Post a Comment