Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. public int insert(int theKey, BinTreeNode root) {
  2.         // insert an element with the specified key
  3.         // overwrite old element if there is already an
  4.         // element with the given key
  5.         // return old element (if any) with key theKey
  6.         // code to be completed
  7.         BinTreeNode p = root, // set p as a pointer
  8.                     pp = null;// set pp as the parent of p
  9.         while(p!=null) {
  10.             pp = p;// move pp to the child
  11.             // move p to the child
  12.             if(p.element > theKey)
  13.                 p = p.left;
  14.             else if(p.element < theKey)
  15.                 p = p.right;
  16.             else {// overwrite old element
  17.                 int returnKey = p.element;
  18.                 p.element = theKey;
  19.                 return returnKey;
  20.             }
  21.         }
  22.         BinTreeNode r = new BinTreeNode(theKey);// create a new node for insert
  23.         if(root != null)// check if the tree is not null
  24.             if(pp.element > theKey)// determine where to insert
  25.                 pp.left = r;
  26.             else
  27.                 pp.right = r;
  28.         else
  29.             root = r;
  30.         return r.element;// return the inserted element
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement