• Interview Preparation
  • πŸš€ Code Day 9 – Binary Search Trees (BST Mastery)

    Welcome to Day 9 of your coding interview journey.

    Yesterday, we introduced Binary Trees.
    Today, we take it one step further into a specialized and very important structure:

    πŸ‘‰ Binary Search Trees (BSTs)


    🧠 What is a Binary Search Tree?

    A Binary Search Tree (BST) is a binary tree with a special property:

    πŸ‘‰ For every node:

    • All values in the left subtree are smaller
    • All values in the right subtree are larger

    Example:

            5
           / \
          3   7
         / \   \
        2   4   8
    

    πŸ”‘ Why BSTs Matter

    BSTs allow efficient operations:

    • Search β†’ O(log n)
    • Insert β†’ O(log n)
    • Delete β†’ O(log n)

    πŸ‘‰ (In balanced cases)


    ⚠️ Important Note

    BST problems often test:

    • Tree traversal
    • Recursion
    • Understanding constraints (not just structure!)

    πŸ’‘ Problem 1 – Validate Binary Search Tree


    🧩 Problem

    Given the root of a binary tree:

    πŸ‘‰ Determine if it is a valid BST


    ❌ Common Mistake

    Many people only compare:

    node.left < node < node.right
    

    ❌ This is NOT enough!


    🧠 Key Insight

    Each node must respect a range:

    • Left subtree β†’ (min, node.val)
    • Right subtree β†’ (node.val, max)

    πŸ› οΈ Solution in Python

    def is_valid_bst(root):
        def helper(node, low, high):
            if not node:
                return True
    
            if not (low < node.val < high):
                return False
    
            return (
                helper(node.left, low, node.val) and
                helper(node.right, node.val, high)
            )
    
        return helper(root, float("-inf"), float("inf"))
    

    ⚑ Complexity

    • Time: O(n)
    • Space: O(h)

    🎯 Key Insight

    πŸ‘‰ Always think in ranges, not just parent-child comparisons


    πŸ’‘ Problem 2 – Lowest Common Ancestor (LCA) in BST


    🧩 Problem

    Given a BST and two nodes p and q:

    πŸ‘‰ Find their lowest common ancestor

    (The lowest node that has both as descendants)


    Example:

            6
           / \
          2   8
         / \ 
        0   4
           / \
          3   5
    

    πŸ‘‰ LCA of 2 and 8 β†’ 6
    πŸ‘‰ LCA of 3 and 5 β†’ 4


    🧠 Key Insight (BST Advantage)

    Because it’s a BST:

    • If both values are smaller β†’ go left
    • If both are larger β†’ go right
    • Otherwise β†’ current node is the LCA

    πŸ› οΈ Solution in Python

    def lowest_common_ancestor(root, p, q):
        while root:
            if p.val < root.val and q.val < root.val:
                root = root.left
            elif p.val > root.val and q.val > root.val:
                root = root.right
            else:
                return root
    

    ⚑ Complexity

    • Time: O(h)
    • Space: O(1) (iterative)

    🎯 Why This Works

    πŸ‘‰ BST property lets us skip entire subtrees

    This is much faster than general binary tree solutions.


    ⚠️ Common Mistakes

    • ❌ Ignoring BST properties
    • ❌ Using generic tree logic (slower)
    • ❌ Forgetting edge cases (same node, root as LCA)
    • ❌ Not validating full subtree ranges

    πŸ§ͺ Practice Problems

    To master BSTs, try:

    1. Insert into BST
    2. Delete node in BST
    3. Kth smallest element in BST
    4. Convert sorted array to BST
    5. BST iterator

    🎯 Key Takeaways

    • BSTs = ordered trees
    • Always leverage:
      • Left < Node < Right
    • Think in:
      • Ranges (validation)
      • Direction (search & LCA)

    πŸš€ Your Challenge (Day 9)

    Solve this:

    Find the Kth smallest element in a BST.

    (Hint: in-order traversal πŸ˜‰)


    πŸ“Œ Final Thoughts

    BSTs are extremely common in interviews because they combine:

    • Trees
    • Searching
    • Optimization

    Mastering them puts you ahead of many candidates.

    3 mins