SERIES
Trees
Teach tree traversal and manipulation — DFS, BFS, recursion over subtrees.
In this seriesNEWSLETTER
01
Invert Binary Tree: recursion as a natural fit
Inverting a binary tree is one of those problems where the recursive solution writes itself once you see it: swap the children, then recurse into each. The iterative version with a queue works too — it's just less obvious why you'd use it here.Jun 13, 2026 · 11 min read · #00030
02
Maximum Depth of Binary Tree: height as a post-order computation
The depth of a tree equals 1 plus the maximum depth of its subtrees. That's a post-order traversal: process children before the parent. Three approaches exist — recursive (cleanest), iterative DFS with a stack (same traversal, different machinery), and BFS where depth equals the level count.Jun 13, 2026 · 10 min read · #00031
03
Binary Tree Level Order Traversal: BFS with a level size snapshot
BFS on a tree processes nodes level by level. The trick for grouping them into separate lists is to snapshot the queue size at the start of each level — every node in that batch belongs to the same level, regardless of how many new nodes they enqueue.Jun 13, 2026 · 10 min read · #00032
04
Same Tree: two trees, one recursive question
Checking whether two binary trees are identical reduces to a single recursive question asked at every node pair. The DFS solution is three base cases and one return statement. But the BFS alternative — processing both trees level by level in a shared queue — is worth understanding, and the edge cases hide a few details that trip people up.Jun 14, 2026 · 10 min read · #00033
05
Subtree of Another Tree: when Same Tree becomes a subproblem
LeetCode 572 asks whether one binary tree appears as a connected subtree inside another. The brute-force DFS solution reuses the Same Tree check from problem 100 — clean and enough for the given constraints. A string-serialization approach cuts the asymptotic cost but adds a sharp correctness trap that most implementations get wrong.Jun 14, 2026 · 10 min read · #00034
06
Validate Binary Search Tree: why checking only the parent is wrong
The classic mistake is comparing a node only against its direct parent. A valid BST enforces a global ordering constraint that propagates down the entire subtree — and the cleanest way to capture that is to carry valid bounds through every recursive call.Jun 14, 2026 · 10 min read · #00035
07
Kth Smallest Element in a BST: in-order traversal as a sorted stream
A BST's in-order traversal visits nodes in ascending order. To find the kth smallest you don't need to collect everything — you stop the moment you hit the kth node. The trick is knowing that stopping early is both safe and sufficient.Jun 14, 2026 · 10 min read · #00036
Occasional notes on what I'm building
Get an email when I publish a new post — engineering write-ups, no spam. Unsubscribe anytime.