Example #1
0
    public TreeNode remove(I t, TreeNode n) {
      if (t == null) {
        throw new RuntimeException("Node not found with data: " + t);
      }
      if (n == null) {
        throw new RuntimeException("Invalid node!");
      }

      I x = n.data;

      if (n.left != null || n.right != null) {
        if (x.compareTo(t) < 0) {
          n.left = remove(t, n.left);

        } else if (x.compareTo(t) > 0) {
          n.right = remove(t, n.right);

        } else if (n.left != null && n.right != null) { // Two children
          // n.data = findMin( n.right ).element;
          // n.right = removeMin( n.right );
        } else {
          n = (n.left != null) ? n.left : n.right;
        }
      } else {
        n = null;
      }
      return n;
    }
Example #2
0
 public BinarySearchTree<I> add(I data) {
   TreeNode node = this.root;
   if (data == null) {
     return this;
   }
   if (node == null || node.data == null) {
     this.root = new TreeNode(data);
     return this;
   }
   while (node != null) {
     // p("comparing " + data + " with " + node.data + " = "
     // + data.compareTo(node.data));
     if (data.compareTo(node.data) == 0) {
       // I found my place in heaven - the search is over
       // p("got it: " + data);
       node = null;
     } else if (data.compareTo(node.data) < 0) {
       // The poor ones go to the south left
       if (node.left != null) {
         // p("left: " + node.left);
         node = node.left;
       } else {
         node.left = new TreeNode(data);
         // p("set left: " + node.left);
         break;
       }
     } else if (data.compareTo(node.data) > 0) {
       // The rich ones go to the north right
       if (node.right != null) {
         // p("right: " + node.right);
         node = node.right;
       } else {
         node.right = new TreeNode(data);
         // p("set right: " + node.right);
         break;
       }
     }
   }
   return this;
 }