Describe how a Binary Search Tree (BST) is implemented and used.

Instruction: Explain the structure of a BST and its common operations.

Context: This question probes the candidate's knowledge of Binary Search Trees, focusing on their implementation and the efficiency of operations such as search, insertion, and deletion.

Updated

Official answer

A binary search tree stores keys in nodes with left and right child references. Under a distinct-key convention, every key in a node's left subtree is smaller and every key in its right subtree is larger; checking only immediate children is not enough.

Search compares at each node and chooses one subtree. Insertion follows that path to an empty child position. Decide what a duplicate means: reject it, update the existing value, or maintain an explicit count. Do not mix policies silently.

Deletion has three cases: remove a leaf; replace a node with its one child; or, for two children, replace its key/value with its in-order successor (minimum of the right subtree) and then remove that successor from its old position. Parent links or the root reference must be updated consistently.

Each operation is O(h) for tree height h. An ordinary BST can become a chain after sorted insertions and take O(n) time; self-balancing variants maintain logarithmic height using rotations and other invariants. In-order traversal produces sorted keys in O(n) time.

Test root deletion, missing keys, all three deletion cases and the global ordering invariant. Use an ordered tree when range queries or ordered iteration matter; a hash map offers a different access/ordering tradeoff.

Related Questions