java - Count number of Insertions in BST -
i have bst class of strings global variable called numinsertions counts number of insertions bst. not sure gives correct results not know recursion well, please me verify
public void insert(string key) { if(isempty()) { root = new node(key); numinsertions++; } else numinsertions = 1+insert(key, root); } public int insert(string key, node curr) { int result = 1; if(key.compareto(curr.getkey())<0) { if(curr.getleftchild()==null) { node newnode = new node(key); curr.setleftchild(newnode); } else result = result +insert(key,curr.getleftchild()); } else { if(curr.getrightchild()==null) { node newnode = new node(key); curr.setrightchild(newnode); } else result = result +insert(key,curr.getrightchild()); } return result; }
write test case class , test class behaving properly. let's class named bst , can access instance variable 'numberofinserts' method named 'size()', simple test case testing insertions (without 3rd party libraries) placed in main method of test class. like:
bst bst = new bst(); //test insertion of 100 items ( int = 0; < 100; i++ ){ bst.insert(string.valueof(i)); if ( bst.size() != i+1 ){ throw new exception("invalid bst size " + bst.size()); } } in example, exception thrown if class not behave properly. if misbehaves, can step debugger (or use system.out.println) try , debug application.
Comments
Post a Comment