Insert the elements 18, 23, 10, 12, 30, 18, 25, 4, 21, 36, 14, 20, 47 into a balanced Binary Search Tree and count the number of comparisons.


Q.) Insert the elements 18, 23, 10, 12, 30, 18, 25, 4, 21, 36, 14, 20, 47 into a balanced Binary Search Tree and count the number of comparisons.

Subject: data structures

A Binary Search Tree (BST) is a tree in which all the nodes follow the below property:

  • The left sub-tree of a node has a key less than or equal to its parent node's key.
  • The right sub-tree of a node has a key greater than to its parent node's key.

To insert elements into a balanced Binary Search Tree (BST), we follow these steps:

  1. Start from the root.
  2. Compare the inserting element with root, if less than root, then recurse for the left subtree. Else, recurse for the right subtree.
  3. After reaching null, insert the new node at that point.

Let's insert the elements 18, 23, 10, 12, 30, 18, 25, 4, 21, 36, 14, 20, 47 into a balanced Binary Search Tree and count the number of comparisons.

Insertion Tree Structure Comparisons
18 18 0
23 18 - 23 1
10 10 - 18 - 23 2
12 10 - 12 - 18 - 23 3
30 10 - 12 - 18 - 23 - 30 4
18 10 - 12 - 18 - 18 - 23 - 30 5
25 10 - 12 - 18 - 18 - 23 - 25 - 30 6
4 4 - 10 - 12 - 18 - 18 - 23 - 25 - 30 7
21 4 - 10 - 12 - 18 - 18 - 21 - 23 - 25 - 30 8
36 4 - 10 - 12 - 18 - 18 - 21 - 23 - 25 - 30 - 36 9
14 4 - 10 - 12 - 14 - 18 - 18 - 21 - 23 - 25 - 30 - 36 10
20 4 - 10 - 12 - 14 - 18 - 18 - 20 - 21 - 23 - 25 - 30 - 36 11
47 4 - 10 - 12 - 14 - 18 - 18 - 20 - 21 - 23 - 25 - 30 - 36 - 47 12

So, the total number of comparisons made to insert these elements into a balanced Binary Search Tree is 12.

Note: The above tree structures are simplified for the sake of understanding. In a real BST, each node only has up to 2 children, and the actual layout would look more like a tree. However, the order of the nodes would remain the same.