class BinSearchTree {
  public static class Node {
    private Comparable value;
    private Node left;
    private Node right;
    private Node(Comparable value) {
      this.value = value;
      this.left = this.right = null;
    }
    public String toString() {
      return "Node(" + value + ")"; 
    }
    private static void toString(StringBuilder buf, Node root) {
      if (root == null)
        return;
      toString(buf, root.left);
      buf.append(root.value);
      buf.append(" ");
      toString(buf, root.right);
    }
    private static Node insert(Comparable value, Node root) {
      if (root == null)
        return new Node(value);
      int cmp = root.value.compareTo(value);
      if (cmp < 0)
        root.right = insert(value, root.right); 
      else
        root.left = insert(value, root.left);
      return root;
    }
    private static Node remove(Comparable value, Node root) {
      if (root == null)
        return null;
      int cmp = root.value.compareTo(value);
      if (cmp == 0) {
        if (root.left == null)
          return root.right;
        if (root.right == null)
          return root.left;
        Node n = searchLargestNode(root.left);
        n.right = root.right;
        return root.left;
      } else if (cmp < 0)
        root.right = remove(value, root.right); 
      else
        root.left = remove(value, root.left);
      return root;
    }
    private static Node searchLargestNode(Node root) {
      if (root.right == null)
        return root;
      return searchLargestNode(root.right);
    }
  }

  private Node rootNode;
  public BinSearchTree() {
    rootNode = null;
  }
  public void insert(Comparable value) {
    rootNode = Node.insert(value, rootNode);
  }
  public void remove(Comparable value) {
    rootNode = Node.remove(value, rootNode);
  }
  public String toString() {
    StringBuilder buf = new StringBuilder();
    buf.append("[");
    Node.toString(buf, rootNode);
    buf.append("]");
    return buf.toString();
  }
}

class Main {
  public static void main(String[] args) {
    BinSearchTree tree1 = new BinSearchTree();
    for (int i = 0; i < 10; i++) {
      tree1.insert((int)(Math.random() * 100));
    }
    System.out.println(tree1);
    
    BinSearchTree tree2 = new BinSearchTree();
    tree2.insert(20);
    tree2.insert(30);
    tree2.insert(10);
    tree2.remove(20);
    System.out.println(tree2);
  }
}
