Skip to lesson

Topic set: trees, heaps and tries

Hierarchical and priority data structures solve search, streaming rank, and prefix matching challenges. We master recursive tree decomposition, heap priority queues, and prefix tries.

Recursive tree decomposition versus naive flattening

Recursive tree decomposition solves a tree problem on the left subtree, on the right subtree, and combines the two answers at the root.

Java
int maxDepth(TreeNode root) {    if (root == null) return 0;          // empty tree: depth 0    int left = maxDepth(root.left);      // solve the left subtree    int right = maxDepth(root.right);    // solve the right subtree    return 1 + Math.max(left, right);    // combine at the root}

A common anti-pattern for tree problems—such as checking if a binary tree is symmetric, finding maximum depth, or inverting a tree—is serializing the entire tree into an auxiliary list or 2D level matrix before solving. While this can work, it wastes O(N) auxiliary heap memory and obscures the natural recursive structure of trees.

Binary trees are inherently recursive: a binary tree is either null, or a root node with two binary subtrees. Most tree challenges decompose cleanly using bottom-up divide-and-conquer: solve the problem on the left subtree, solve the problem on the right subtree, and combine the results at the root. For example, the maximum depth of a binary tree is simply 1 + Math.max(maxDepth(root.left), maxDepth(root.right)) with base case root == null returning 0. This bottom-up decomposition visits each node exactly once in O(N) time and consumes O(H) auxiliary stack space, where H is the tree height.

Binary search tree invariants and in-order traversals

A Binary Search Tree (BST) enforces a strict structural invariant: for every node, all values in its left subtree are strictly smaller than root.val, and all values in its right subtree are strictly greater than root.val.

Example 1 · Lowest Common Ancestor in a BST

LowestCommonAncestorBstDemo.javaJava
public class LowestCommonAncestorBstDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int val) { this.val = val; }    }
    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        if (p.val < root.val && q.val < root.val) {            return lowestCommonAncestor(root.left, p, q);        } else if (p.val > root.val && q.val > root.val) {            return lowestCommonAncestor(root.right, p, q);        } else {            return root; // Split point is the LCA        }    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(6);        root.left = new TreeNode(2);        root.right = new TreeNode(8);        root.left.left = new TreeNode(0);        root.left.right = new TreeNode(4);
        TreeNode p = root.left; // 2        TreeNode q = root.left.right; // 4        TreeNode lca = lowestCommonAncestor(root, p, q);        System.out.println("LCA of 2 and 4: " + lca.val);    }}
Output
LCA of 2 and 4: 2

What this code does

  • Both 2 and 4 reside in the left subtree of 6.
  • At node 2, 2 equals p, so 2 is the split point and LCA.
  • Executes in O(H) time without visiting the right subtree.

A common beginner mistake when validating a BST is only checking local parent-child relationships: root.left.val < root.val and root.right.val > root.val. This check fails on trees where a right child's left descendant is smaller than the grandparent root (e.g. root 5, right child 6, right child's left 4). To validate a BST correctly, you must pass valid range boundaries down the recursion: validate(root, minBound, maxBound). Alternatively, an in-order traversal (Left, Root, Right) of a BST visits nodes in strictly ascending sorted order. Checking that each visited node is strictly greater than the predecessor node validates the BST in O(N) time.

Priority queues: streaming top-k without full sorting

When finding the Kth largest element in a stream of N numbers, a naive approach collects all elements in a list and sorts them in O(N log N) time on every query. If N is one million and K is ten, sorting the entire dataset repeatedly is unacceptably slow.

A min-heap of fixed size K provides the optimal streaming solution. We maintain a PriorityQueue<Integer> storing only the K largest elements seen so far. For every incoming element x, we offer x into the heap. If the heap size exceeds K, we poll the minimum element from the top.

Because the heap size never exceeds K + 1, each insertion and deletion runs in O(log K) time. The overall processing time for N elements is O(N log K), and the heap top always exposes the Kth largest element in O(1) time. When K is much smaller than N, O(N log K) is vastly superior to full O(N log N) sorting.

Example 2 · Kth Largest Element in a Stream via Min-Heap

KthLargestElementStreamDemo.javaJava
import java.util.*;
public class KthLargestElementStreamDemo {    static class KthLargest {        private PriorityQueue<Integer> minHeap = new PriorityQueue<>();        private int k;
        public KthLargest(int k, int[] nums) {            this.k = k;            for (int x : nums) add(x);        }
        public int add(int val) {            minHeap.offer(val);            if (minHeap.size() > k) minHeap.poll();            return minHeap.peek();        }    }
    public static void main(String[] args) {        int[] init = {4, 5, 8, 2};        KthLargest kl = new KthLargest(3, init); // elements {4, 5, 8} in minHeap        System.out.println("Add 3: " + kl.add(3)); // 4        System.out.println("Add 5: " + kl.add(5)); // 5        System.out.println("Add 10: " + kl.add(10)); // 5    }}
Output
Add 3: 4
Add 5: 5
Add 10: 5

What this code does

  • Min-heap keeps the top 3 largest elements.
  • After adding 3, top 3 are {4, 5, 8}, 3rd largest is 4.
  • Adding 10 evicts 4, top 3 become {5, 5, 10}, 3rd largest is 5.

Tries: prefix matching and dictionary search

A Trie (prefix tree) is a specialized tree structure optimized for string retrieval and prefix matching. If you have a dictionary of N words of length L, testing whether any word begins with prefix P using a linear list scan takes O(N * |P|) string comparisons.

A Trie stores characters along tree edges or child node arrays of size 26 (for lowercase English letters). Each node represents a prefix formed by the path from the root. To insert a word, we traverse or create child nodes down L levels and mark the terminating node with isEndOfWord = true.

Searching for a word or prefix of length L requires traversing exactly L node pointers, taking strictly O(L) time—completely independent of the total dictionary size N. Tries power search autocompletion, spell checkers, and Boggle solvers with lightning-fast prefix validation.

Example 3 · Prefix Trie Implementation

PrefixTrieDemo.javaJava
public class PrefixTrieDemo {    static class TrieNode {        TrieNode[] children = new TrieNode[26];        boolean isEnd = false;    }
    private TrieNode root = new TrieNode();
    public void insert(String word) {        TrieNode curr = root;        for (char c : word.toCharArray()) {            int idx = c - 'a';            if (curr.children[idx] == null) curr.children[idx] = new TrieNode();            curr = curr.children[idx];        }        curr.isEnd = true;    }
    public boolean search(String word) {        TrieNode node = find(word);        return node != null && node.isEnd;    }
    public boolean startsWith(String prefix) {        return find(prefix) != null;    }
    private TrieNode find(String s) {        TrieNode curr = root;        for (char c : s.toCharArray()) {            int idx = c - 'a';            if (curr.children[idx] == null) return null;            curr = curr.children[idx];        }        return curr;    }
    public static void main(String[] args) {        PrefixTrieDemo trie = new PrefixTrieDemo();        trie.insert("report");        System.out.println("Search report: " + trie.search("report"));        System.out.println("Search rep: " + trie.search("rep"));        System.out.println("StartsWith rep: " + trie.startsWith("rep"));    }}
Output
Search report: true
Search rep: false
StartsWith rep: true

What this code does

  • report is inserted with isEnd = true at the terminating 't'.
  • search('rep') returns false because 'p' is not marked as end of word.
  • startsWith('rep') returns true because the prefix path exists.

Next step

Check your understanding

10 quick questions