Data Structures and Algorithms • C# examples
Binary Search Trees
Maintain an ordering invariant to support search, insertion, and deletion.
Concept
A binary search tree places smaller keys in one subtree and larger keys in the other, according to its duplicate policy. Search and update follow one root-to-leaf path. If insertion order is already sorted, an unbalanced tree can become a chain and lose its expected efficiency.
How to approach it
Define duplicate handling and update parent/child links carefully during deletion of leaf, one-child, and two-child nodes.
Complexity
Operations O(h), where h is tree height; worst-case h is n, balanced h is O(log n).
C# example
static bool Contains(Node? node, int target)
{
while (node is not null)
{
if (target == node.Value) return true;
node = target < node.Value ? node.Left : node.Right;
}
return false;
}
Expected result or behavior
Each comparison chooses the only subtree that can contain the target.
Practice exercise
Explain why sorted insertion produces a poor-height tree and name a remedy.
Key takeaway: BST performance depends on height; ordering alone does not guarantee balance.