1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 5

CAP7004 · Unit 5: Trees

Binary search trees

8 practice questions

Key points

  • Left < node < right; inorder is sorted
  • Search/insert/delete cost O(height)
  • Two-child delete uses inorder successor
  • Sorted insert order makes a skewed tree

A binary search tree (BST) keeps, for every node, all keys in the left subtree smaller and all keys in the right subtree larger (no duplicates in the basic form).

Key property: an inorder traversal visits keys in sorted order.

Operations (h = height):

  • Search, insert, minimum, maximum: O(h). Follow left or right by comparing keys. Minimum is the leftmost node, maximum the rightmost.
  • Delete has three cases: a leaf is removed; a node with one child is replaced by that child; a node with two children is replaced by its inorder successor (the minimum of the right subtree) or predecessor, then that node is removed.
  • Inorder successor of 8 in the tree below is 10.

Inserting 8, 3, 10, 1, 6, 14, 4, 7, 13 gives preorder 8 3 1 6 4 7 10 14 13, inorder 1 3 4 6 7 8 10 13 14, and height 3.

Balance matters: a balanced BST has h = O(log n). Inserting sorted keys 1, 2, 3, 4, 5 creates a chain of height 4, so operations become O(n). Self-balancing trees (AVL, red-black) prevent this.

Exam pitfall: to delete a node with two children, copy its inorder successor into it and then delete the successor, which has at most one child; do not just remove the node.

Try two questions

Question 1 · Tier 3, Apply

In the same BST, the inorder successor of 8 is:

  1. 13
  2. 14
  3. 10
  4. 7
Show the answer

C. The minimum of the right subtree {10, 14, 13} is 10.

Question 2 · Tier 1, Recall

Which traversal of a BST outputs the keys in sorted order?

  1. Postorder
  2. Level order
  3. Inorder
  4. Preorder
Show the answer

C. Left subtree, node, right subtree yields ascending order.