Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public int insert(int theKey, BinTreeNode root) {
- // insert an element with the specified key
- // overwrite old element if there is already an
- // element with the given key
- // return old element (if any) with key theKey
- // code to be completed
- BinTreeNode p = root, // set p as a pointer
- pp = null;// set pp as the parent of p
- while(p!=null) {
- pp = p;// move pp to the child
- // move p to the child
- if(p.element > theKey)
- p = p.left;
- else if(p.element < theKey)
- p = p.right;
- else {// overwrite old element
- int returnKey = p.element;
- p.element = theKey;
- return returnKey;
- }
- }
- BinTreeNode r = new BinTreeNode(theKey);// create a new node for insert
- if(root != null)// check if the tree is not null
- if(pp.element > theKey)// determine where to insert
- pp.left = r;
- else
- pp.right = r;
- else
- root = r;
- return r.element;// return the inserted element
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement