๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Medium Coding Patterns: Trees, Graphs, and BSTs

Python InterviewCoding Challengesโญ Premium
Python Interview ยท Difficulty: Medium

Medium questions reward a small toolkit applied precisely

The medium round is where most candidates are decided. The problems are no longer solvable by pattern-matching one sentence to one function; they ask you to choose between traversals, carry state through recursion, or model prerequisites as a graph. The good news is that the entire medium tier for trees and graphs rests on a handful of engines โ€” inorder, preorder, level-order BFS, DFS with a visited set, Kahn's algorithm โ€” and the differences between problems are mostly about what state you record at each step. This lesson builds those engines once, then shows how the common interview questions are configurations of them.

Prerequisites

  • !Recursion and basic data structures
  • !The two-pointer and hash-map patterns from the easy round

What You'll Learn

  • 1Write iterative inorder, preorder, and level-order traversals without recursion bugs
  • 2Validate a BST with min/max bounds and find the kth smallest element efficiently
  • 3Represent graphs as adjacency lists and run BFS, DFS, and path checks
  • 4Detect cycles and compute topological order with Kahn's algorithm

Trees: traversals you should be able to write cold

A binary tree node holds a value and two children; every tree question is some traversal with extra bookkeeping. Inorder visits left, root, right โ€” for a BST that yields values in sorted order, which is why kth-smallest is just an inorder walk that counts. The iterative inorder version uses an explicit stack: descend left pushing nodes, pop, record, then move right. Preorder visits root first and pairs naturally with a stack that pushes right before left so the left branch pops first. Level-order uses a deque, snapshotting the queue length at each level to separate levels in the output.

Recursive traversals are fine โ€” Python's default recursion limit is generous for balanced trees โ€” but state the space cost as O(h) for the call stack and switch to iterative when the interviewer mentions skewed trees or extremely deep structures. Zigzag level order is level order plus a direction flag, appending to the left or the right of a deque. Serialization via level order with null markers, followed by deserialization with a queue of pending parents, round-trips any binary tree and is a strong follow-up answer.

python
from collections import deque


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def inorder_iterative(root):
    """Left, root, right โ€” iterative, O(h) space."""
    result, stack, current = [], [], root
    while current or stack:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        result.append(current.val)
        current = current.right
    return result


def level_order(root):
    """BFS with per-level grouping, O(n) time and space."""
    if not root:
        return []
    levels = []
    queue = deque([root])
    while queue:
        size = len(queue)
        level = []
        for _ in range(size):
            node = queue.popleft()
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        levels.append(level)
    return levels

Binary search trees: invariants carry the answers

A BST's invariant โ€” every node in the left subtree is strictly less, every node in the right strictly greater โ€” is global, not local. Validation therefore threads a min/max window down the recursion: each node must sit strictly between the bounds inherited from its ancestors, then passes its own value as the tightened bound to its children. Checking only parent-child pairs is the classic bug; a right descendant smaller than the root but larger than its parent will slip through a local-only check.

That same invariant makes search, insert, and delete logarithmic on balanced trees and linear on degenerate ones โ€” mention the balance caveat when you quote complexities. Kth-smallest exploits the sorted inorder property: walk inorder, decrement k, return when k hits zero, O(h + k) time. Lowest common ancestor in a BST is a directional walk: while both targets are smaller go left, while both are larger go right, and the first node where the directions diverge is the answer. Delete with two children finds the inorder successor in the right subtree, copies its value, and removes the successor โ€” a three-case routine worth practicing until it is automatic.

python
def validate_bst(root, low=float("-inf"), high=float("inf")):
    """Range-threaded validation; O(n) time, O(h) space."""
    if not root:
        return True
    if not (low < root.val < high):
        return False
    return (validate_bst(root.left, low, root.val)
            and validate_bst(root.right, root.val, high))


def kth_smallest(root, k):
    """Inorder walk counting down k."""
    stack, current, count = [], root, 0
    while stack or current:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        count += 1
        if count == k:
            return current.val
        current = current.right
    raise ValueError("k out of range")


def lca_bst(root, p, q):
    """Descend while both targets agree on direction."""
    node = root
    while node:
        if p < node.val and q < node.val:
            node = node.left
        elif p > node.val and q > node.val:
            node = node.right
        else:
            return node
    return None

Graphs: adjacency lists, BFS, and DFS

Represent a graph as a dict mapping each vertex to a list of neighbors; add weights by storing tuples. BFS uses a deque and a visited set, marking nodes when they are enqueued โ€” marking on dequeue floods the queue with duplicates. DFS uses an explicit stack or recursion with the same visited discipline. Both run in O(V + E) time and O(V) space. Path existence is BFS that stops the moment the destination is dequeued; connected components run a full traversal from each unvisited vertex.

Cycle detection differs by graph type, and interviewers will test whether you know the difference. Undirected graphs: DFS carrying the parent, declaring a cycle when you meet an already-visited neighbor that is not the parent. Directed graphs: three-color DFS (white unvisited, gray on the current path, black finished) declaring a cycle when a gray neighbor is reached โ€” or simply run Kahn's algorithm and check whether every vertex received an ordering. Both directed and undirected versions are worth practicing; mixing them up is a common rejection cause.

python
from collections import defaultdict, deque


def bfs(graph, start):
    """Level-order graph traversal, O(V + E)."""
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order


def has_path(graph, source, target):
    """Unweighted shortest-path existence via BFS."""
    if source == target:
        return True
    visited = {source}
    queue = deque([source])
    while queue:
        node = queue.popleft()
        for neighbor in graph[node]:
            if neighbor == target:
                return True
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return False


def has_cycle_undirected(graph):
    """DFS with parent tracking for undirected graphs."""
    visited = set()

    def dfs(node, parent):
        visited.add(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                if dfs(neighbor, node):
                    return True
            elif neighbor != parent:
                return True
        return False

    for vertex in graph:
        if vertex not in visited and dfs(vertex, None):
            return True
    return False

Topological sort and the course-schedule family

When tasks have prerequisites, model them as a directed graph and compute a topological order โ€” any linear ordering where every edge points forward. Kahn's algorithm computes it with in-degrees: enqueue every vertex with in-degree zero, pop one, append it to the result, decrement its neighbors' in-degrees, and enqueue any that reach zero. If the result covers fewer vertices than the graph has, a cycle exists and no valid order is possible.

The course-schedule questions are direct applications. Can-finish-all-courses is exactly cycle detection via Kahn: if you can order every course, the prerequisites form a DAG. Course-schedule-two asks for the ordering itself. Build-time estimation with dependencies adds a longest-path computation on top. When you present Kahn's algorithm, mention that depth-first post-order reversal is the alternative โ€” interviewers sometimes ask you to implement that version, so knowing both protects you.

Construction, symmetry, and follow-up pressure

Construction from traversal arrays tests divide-and-conquer: the first preorder value is the root; find it in inorder to split left and right subtrees; recurse on the slices. Symmetry checks run two pointers down mirrored subtrees simultaneously. Diameter of a tree combines depth computation with a global maximum โ€” each node contributes left-depth plus right-depth. Expect follow-ups that change the data: what if values repeat? What if the tree is enormous and must be streamed? What if edges are weighted, so BFS gives the wrong shortest path and Dijkstra is required? Answering "then we switch to Dijkstra or Bellman-Ford depending on negative weights" shows range beyond the script you memorized.

Question familyEngineKey state
TraversalsStack or queue walkVisit order
Validate BSTInorder or range recursionmin/max bounds
Kth smallestInorder countdecrementing k
Path existenceBFSvisited set
Cycle, undirectedDFSparent node
Cycle, directed / topologicalKahn or three-color DFSin-degrees or colors
Build from traversalsRecursionroot discovery + split index

Common Mistakes

Marking BFS nodes visited when dequeued

Fix: Mark on enqueue to prevent duplicate queue entries

Validating BSTs by comparing only with the direct parent

Fix: Thread min/max bounds down from the root; distant ancestors constrain distant descendants

Using a directed-graph cycle check on an undirected graph

Fix: Undirected DFS compares against the parent; directed needs in-degrees or gray/black coloring

Slicing preorder and inorder lists repeatedly without indexing

Fix: Use index ranges or a value-to-index map to keep construction O(n)

Best Practices

  • State the traversal and its complexity before writing code
  • Ask whether the graph is directed, weighted, and connected โ€” the answers change the algorithm
  • Write iterative traversals when recursion depth is a concern; mention the trade-off either way
  • Use deque for queues and defaultdict(list) for adjacency; they are the expected tools

Interview Questions

Q1: Recursive versus iterative tree traversal โ€” which do you prefer?

Recursive is clearer and fine for balanced trees at O(h) stack depth. Iterative avoids recursion-limit and stack-overflow risk on skewed trees and shows you understand the explicit stack the interpreter maintains for you.

Q2: Why must BST validation carry min and max bounds?

The BST property is global: every descendant must respect all ancestors, not just its parent. Bounds propagate the full constraint chain, catching violations that local comparisons miss.

Q3: BFS or DFS for a given graph problem?

BFS for shortest paths in unweighted graphs and level-order results. DFS for connectivity, cycle detection, topological sorting via post-order, and exhaustive search with pruning. Both are O(V + E).

Q4: How does Kahn's algorithm detect a cycle?

It repeatedly removes in-degree-zero vertices. If a cycle exists, its members always retain in-degree at least one, so the processed count falls short of the total vertex count.

Q5: How would you find the diameter of a binary tree?

A DFS that returns the height of each subtree while updating a global maximum of left-height plus right-height at every node, overall O(n) time and O(h) space.

Key Takeaways

  • Medium tree and graph problems are configurations of a few traversal engines
  • Iterative inorder, level-order BFS, and Kahn's sort are worth perfecting first
  • BST answers flow from the global ordering invariant โ€” bounds or inorder order
  • Mark BFS visited on enqueue; track parents for undirected cycles, colors or in-degrees for directed
  • Topological sort turns prerequisite questions into cycle detection
  • Always ask about direction, weights, and scale before choosing the algorithm
๐Ÿ”’

Premium Content

Medium Coding Patterns: Trees, Graphs, and BSTs

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement