Skip to main content
LeetCode Prep
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. 1. All nodes in the Left Subtree must be strictly LESS than the parent node's value.
  1. 2. All nodes in the Right Subtree must be strictly GREATER than the parent node's value.
*(Assuming no duplicate values allowed).*

*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 check if 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
12345678910111213141516
def isValidBST(root):
    def validate(node, low, high):
        if not node:
            return True # Empty nodes are valid
            
        # The node's value must stay within the strict boundaries
        if not (low < node.val < high):
            return False
            
        # Left child: Upper bound becomes the current node's value
        # Right child: Lower bound becomes the current node's value
        return (validate(node.left, low, node.val) and 
               validate(node.right, node.val, high))
               
    # Start with absolute infinity as bounds
    return validate(root, float(&#039;-inf'), float('inf'))

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).
*Unlike a BST, the left child is NOT guaranteed to be smaller than the right child.*

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. 1. Maintain a Min-Heap of size K.
  1. 2. Iterate through the array, pushing elements into the Heap.
  1. 3. If the Heap size exceeds K, pop() the minimum element.
  1. 4. At the end, the Heap will contain exactly the K largest elements. Because it's a Min-Heap, the smallest of those K largest elements (which is the exact Kth largest overall) will be sitting at the very top of the heap!
python
1234567891011
import heapq

def findKthLargest(nums, k):
    min_heap = []
    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap) # Kick out the smallest number
            
    return min_heap[0] # The Kth largest is at the top
# Time: O(N log K), Space: O(K)

8. Mini Project: Merge K Sorted Lists

*Prompt:* You are given an array of K linked-lists, each sorted in ascending order. Merge all the linked-lists into one sorted linked-list. *Logic:*
  1. 1. Create a Min-Heap.
  1. 2. Put the head node of all K lists into the heap.
  1. 3. While the heap is not empty:
  1. 4. Pop the smallest node. Append it to your final result list.
  1. 5. If that popped node has a next node, push node.next into the heap.
*Time Complexity:* O(N log K), where N is total nodes.

9. Common Mistakes

  • Assuming Python has a Max-Heap: Python's heapq is strictly a Min-Heap. If you need a Max-Heap in Python, you must multiply all numbers by -1 before pushing them in, and multiply by -1 when 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_up array logic for a Heap in an interview. Use PriorityQueue (Java) or heapq (Python).

11. Exercises

  1. 1. What does the array representation of an In-Order traversal look like for a valid BST?
  1. 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 k and an initial array, and requires an add(val) method that returns the current Kth largest element after every insertion." (LeetCode 703).

15. FAQs

  • Q: Are Heaps implemented as Trees or Arrays?
A: Theoretically, they are complete binary trees. Practically, in memory, they are stored as flat Arrays, using math formulas (parent = (i - 1) / 2) to instantly calculate child indices without using pointers.

16. Summary

Binary Search Trees and Heaps enforce mathematical rules on hierarchical data. Use BSTs when you need fast, dynamic lookup, insertion, and deletion while maintaining a sorted structure. Use Heaps (Priority Queues) when you only care about the absolute largest or smallest items (Top K problems). To pass the "Validate BST" question, you must use global MIN and MAX bounds during traversal.

17. Next Chapter Recommendation

Tree traversals relied heavily on Recursion. But recursion is not just for Trees. In Chapter 12: Recursion and Backtracking, we will learn how to use recursion to explore every possible combination of data, solving complex puzzles like Sudoku and generating Permutations.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·