Insert

Node insert(Node root, int val) {
  if (root == null) return new Node(val);
  if (val < root.val) root.left = insert(root.left, val);
  else root.right = insert(root.right, val);
  return root;
}
Advertisement

Search

Node search(Node root, int val) {
  if (root == null || root.val == val) return root;
  return val < root.val ? search(root.left, val) : search(root.right, val);
}
Advertisement

Delete (three cases)

Node delete(Node root, int val) {
  if (root == null) return null;
  if (val < root.val) root.left = delete(root.left, val);
  else if (val > root.val) root.right = delete(root.right, val);
  else {
    if (root.left == null) return root.right;
    if (root.right == null) return root.left;
    // both children: replace with in-order successor
    Node succ = minNode(root.right);
    root.val = succ.val;
    root.right = delete(root.right, succ.val);
  }
  return root;
}

Balanced vs skewed

Balanced: O(log N) ops. Skewed (sorted input): O(N). Motivates self-balancing trees.

Insert

Node insert(Node root, int val) {
  if (root == null) return new Node(val);
  if (val < root.val) root.left = insert(root.left, val);
  else root.right = insert(root.right, val);
  return root;
}

Search

Node search(Node root, int val) {
  if (root == null || root.val == val) return root;
  return val < root.val ? search(root.left, val) : search(root.right, val);
}

Delete (three cases)

Node delete(Node root, int val) {
  if (root == null) return null;
  if (val < root.val) root.left = delete(root.left, val);
  else if (val > root.val) root.right = delete(root.right, val);
  else {
    if (root.left == null) return root.right;
    if (root.right == null) return root.left;
    // both children: replace with in-order successor
    Node succ = minNode(root.right);
    root.val = succ.val;
    root.right = delete(root.right, succ.val);
  }
  return root;
}

Balanced vs skewed

Balanced: O(log N) ops. Skewed (sorted input): O(N). Motivates self-balancing trees.