title: Java binary search tree - incorrectly working insert method
body: <p>I've a binary search tree homework in Java where I was given complete Tree and Node classes and a SearchTree class in which I'm to complete the search and insert methods. The search is supposed to return the value of the node corresponding the searched key.</p>
  
  <p><a href="http://pastebin.com/iy1BL2nv" rel="nofollow">Here</a> is the Tree class and <a href="http://pastebin.com/mVnPU8Yd" rel="nofollow">here</a> the Node class. My search and insert methods are below. </p>
  
  <p>It seems I'm getting close, but test insert of key 0 and value 2 into Tree[Node[0,1,null,null]] results in Tree[Node[0,1,null,null] rather than the correct Tree[Node[0,2,null,null]]. What am I not understanding here?</p>
  
  <pre><code>public static Object search(Tree tree, int key) {
      Node x = tree.getRoot();
      while (x != null) {
          if (key == x.getKey()) {
              return x.getValue();
          }
          if (key &lt; x.getKey()) {
              x = x.getLeft();
          } else {
              x = x.getRight();
          }            
      }
      return null;
  }
  
  public static void insert(Tree tree, int key, Object value) {
      if (tree.getRoot() == null) {
          tree.setRoot(new Node(key, value));
      }
      Node juuri = tree.getRoot();
      while (juuri != null) {
          if (key == juuri.getKey()) {
              return;
          } else if (key &lt; juuri.getKey()) {
              if (juuri.getLeft() == null) {
                  juuri.setLeft(new Node(key, value));
                  return;
              } else {
                  juuri = juuri.getLeft();
              }
          } else {
              if (juuri.getRight() == null) {
                  juuri.setRight(new Node(key, value));
                  return;
              } else {
                  juuri = juuri.getRight();
              }
          }
      }
  }
  </code></pre>