CHAPTER 11
Beginner
Binary Search Trees and Heaps
Updated: May 18, 2026
5 min read
# CHAPTER 11
Binary Search Trees and Heaps
1. Chapter Introduction
A standard Binary Tree is useful, but searching it requires O(N) time. By enforcing strict mathematical sorting rules upon the tree, we unlock the power of Binary Search Trees (BST), allowing O(log N) searches. Furthermore, by enforcing a different set of rules, we create Heaps (Priority Queues), the ultimate data structure for "Top K" problems. This chapter covers validation, searching, and Heap optimizations.2. The Binary Search Tree (BST) Property
A Binary Search Tree is a binary tree where every single node adheres to this strict rule:- 1. All nodes in the Left Subtree must be strictly LESS than the parent node's value.
- 2. All nodes in the Right Subtree must be strictly GREATER than the parent node's value.
*The Superpower:* If you are looking for 7, and you are standing at root 10, you know 100% that 7 CANNOT be in the right subtree. You discard the entire right half of the tree instantly.
Search, Insert, and Delete are O(log N) Time.
3. Pattern 1: Validating a BST
This is a classic "Trick" interview question. *Prompt:* Determine if a binary tree is a valid BST (LeetCode 98). *The Trap:* Candidates checkif node.left.val < node.val. This is wrong. A left child might be smaller than its direct parent, but larger than the root, violating the global BST rule.
*The Solution:* You must pass a global MIN and MAX boundary down the recursion tree.
python
4. The In-Order Traversal Secret
If you run an In-Order DFS Traversal (Left, Node, Right) on a valid Binary Search Tree, the resulting array will be perfectly sorted in ascending order. *Interview Hack:* If you are stuck on a BST problem (like finding the Kth smallest element), just run an In-Order traversal to create a sorted array, and grab the Kth element. (It costs O(N) Space, but guarantees a passing solution).5. What is a Heap?
A Heap (specifically a Min-Heap or Max-Heap) is a complete binary tree that obeys the Heap Property:- Min-Heap: The parent node is always smaller than or equal to its children. (The absolute smallest number in the entire tree is always sitting at the very top, the Root).
- Max-Heap: The parent is always larger than its children. (The biggest number is at the top).
Heap Operations:
- Peek Minimum: O(1) Time. (Just look at the root).
- Insert: O(log N) Time. (Add to bottom, "bubble up").
- Extract Minimum: O(log N) Time. (Remove root, replace with bottom, "bubble down").
6. The Priority Queue (Heap Implementation)
In modern programming languages, you do not build Heaps from scratch using Node classes. They are implemented using arrays under the hood and exposed as Priority Queues.-
Python:
import heapq(Min-Heap by default).
-
Java:
PriorityQueue<Integer> pq = new PriorityQueue<>();
7. Pattern 2: The "Top K" Elements (Heap)
*Rule of Thumb:* Whenever a question asks for the "Kth Largest", "Top K Frequent", or "K Closest" elements, ALWAYS use a Heap. *Prompt:* Find the Kth largest element in an unsorted array. *Brute Force:* Sort the array O(N log N) and pick the Kth index. *Optimized (Min-Heap):*-
1.
Maintain a Min-Heap of size
K.
- 2. Iterate through the array, pushing elements into the Heap.
-
3.
If the Heap size exceeds
K,pop()the minimum element.
-
4.
At the end, the Heap will contain exactly the
Klargest elements. Because it's a Min-Heap, the smallest of thoseKlargest elements (which is the exact Kth largest overall) will be sitting at the very top of the heap!
python
8. Mini Project: Merge K Sorted Lists
*Prompt:* You are given an array ofK linked-lists, each sorted in ascending order. Merge all the linked-lists into one sorted linked-list.
*Logic:*
- 1. Create a Min-Heap.
-
2.
Put the
headnode of allKlists into the heap.
- 3. While the heap is not empty:
- 4. Pop the smallest node. Append it to your final result list.
-
5.
If that popped node has a
nextnode, pushnode.nextinto the heap.
9. Common Mistakes
-
Assuming Python has a Max-Heap: Python's
heapqis strictly a Min-Heap. If you need a Max-Heap in Python, you must multiply all numbers by-1before pushing them in, and multiply by-1when popping them out.
-
BST Unbalanced Nightmare: In the worst-case scenario, if you insert sorted numbers
[1,2,3,4]into a basic BST, it just becomes a straight line (a Linked List). Search time degrades from O(log N) to O(N). Production databases use self-balancing trees (AVL or Red-Black trees) to prevent this.
10. Best Practices
-
Use the standard library: Do not attempt to implement the
bubble_uparray logic for a Heap in an interview. UsePriorityQueue(Java) orheapq(Python).
11. Exercises
- 1. What does the array representation of an In-Order traversal look like for a valid BST?
-
2.
If you push
[5, 2, 8, 1]into a Min-Heap, what number is at the root?
12. MCQs
Question 1
What is the defining mathematical property of a Binary Search Tree (BST)?
Question 2
What is the average Time Complexity for Search, Insert, and Delete in a balanced BST?
Question 3
If you perform an "In-Order" Traversal (Left, Node, Right) on a valid BST, what is guaranteed about the output?
Question 4
What is the fatal trap when writing the "Validate BST" algorithm?
Question 5
What is the defining property of a Min-Heap?
Question 6
What is the Time Complexity of "Peeking" at the minimum element in a Min-Heap?
Question 7
What is the Time Complexity of "Extracting" (Popping) the minimum element from a Min-Heap?
Question 8
What specific phrase in an interview prompt should instantly trigger the thought: "I should use a Heap / Priority Queue"?
Question 9
When finding the "Kth Largest" element in an array of size N, why is maintaining a Min-Heap of size K (O(N log K)) better than sorting the whole array (O(N log N))?
Question 10
How do you simulate a Max-Heap using Python's default heapq (which only provides a Min-Heap)?
14. Interview Questions
-
Q: "Design a class to find the Kth largest element in a stream. The class will be instantiated with
kand an initial array, and requires anadd(val)method that returns the current Kth largest element after every insertion." (LeetCode 703).
15. FAQs
- Q: Are Heaps implemented as Trees or Arrays?
parent = (i - 1) / 2) to instantly calculate child indices without using pointers.