Trees
Reach for it when the problem says
- Hierarchies
- depth
- paths
- BST ordering
- Solved
- 0/39Solved
- Problems
- 39Problems
- Variants
- 7Variants
Problems
7 variantsCompare and mirror
0 of 5 solved- Invert a Binary TreeUp nextSprintDeep diveEasyDecode Invert a Binary Tree
- Same TreeSprintDeep diveEasyDecode Same Tree
- Subtree of Another TreeEasyDecode Subtree of Another Tree
- Symmetric TreeSprintDeep diveEasyDecode Symmetric Tree
- Leaf-Similar TreesEssentialsDeep diveEasyDecode Leaf-Similar Trees
Bottom-up DFS
0 of 6 solved- Maximum Depth of a Binary TreeEssentialsSprintDeep diveEasyDecode Maximum Depth of a Binary Tree
- Balanced Binary TreeEasyDecode Balanced Binary Tree
- Diameter of a Binary TreeEasyDecode Diameter of a Binary Tree
- Lowest Common Ancestor of a Binary TreeEssentialsSprintDeep diveMediumDecode Lowest Common Ancestor of a Binary Tree
- House Robber IIIMediumDecode House Robber III
- Maximum Path SumSprintDeep diveHardDecode Maximum Path Sum
Level-order BFS
0 of 7 solved- Minimum Depth of Binary TreeEasyDecode Minimum Depth of Binary Tree
- Average of Levels in Binary TreeSprintDeep diveEasyDecode Average of Levels in Binary Tree
- Level Order TraversalSprintDeep diveMediumDecode Level Order Traversal
- Right Side ViewEssentialsSprintDeep diveMediumDecode Right Side View
- Maximum Level Sum of a Binary TreeEssentialsDeep diveMediumDecode Maximum Level Sum of a Binary Tree
- Binary Tree Zigzag Level Order TraversalSprintDeep diveMediumDecode Binary Tree Zigzag Level Order Traversal
- All Nodes Distance K in Binary TreeMediumDecode All Nodes Distance K in Binary Tree
BST properties
0 of 6 solved- Search in a Binary Search TreeEssentialsDeep diveEasyDecode Search in a Binary Search Tree
- Minimum Absolute Difference in BSTSprintDeep diveEasyDecode Minimum Absolute Difference in BST
- Validate a Binary Search TreeSprintDeep diveMediumDecode Validate a Binary Search Tree
- Kth Smallest in a BSTSprintDeep diveMediumDecode Kth Smallest in a BST
- Lowest Common Ancestor in a BSTMediumDecode Lowest Common Ancestor in a BST
- Delete Node in a BSTEssentialsDeep diveMediumDecode Delete Node in a BST
Top-down DFS
0 of 5 solved- Path SumSprintDeep diveEasyDecode Path Sum
- Count Good Nodes in Binary TreeEssentialsDeep diveMediumDecode Count Good Nodes in Binary Tree
- Path Sum IIIEssentialsDeep diveMediumDecode Path Sum III
- Longest ZigZag Path in a Binary TreeEssentialsDeep diveMediumDecode Longest ZigZag Path in a Binary Tree
- Sum Root to Leaf NumbersSprintDeep diveMediumDecode Sum Root to Leaf Numbers
Build and reshape
0 of 6 solved- Convert Sorted Array to Binary Search TreeSprintDeep diveEasyDecode Convert Sorted Array to Binary Search Tree
- Construct Binary Tree from Preorder and Inorder TraversalSprintDeep diveMediumDecode Construct Binary Tree from Preorder and Inorder Traversal
- Flatten Binary Tree to Linked ListSprintDeep diveMediumDecode Flatten Binary Tree to Linked List
- Construct Binary Tree from Inorder and Postorder TraversalSprintDeep diveMediumDecode Construct Binary Tree from Inorder and Postorder Traversal
- Construct Quad TreeSprintDeep diveMediumDecode Construct Quad Tree
- Serialize and Deserialize Binary TreeHardDecode Serialize and Deserialize Binary Tree
Tries
0 of 4 solved- Implement Trie (Prefix Tree)EssentialsSprintDeep diveMediumDecode Implement Trie (Prefix Tree)
- Design Add and Search Words Data StructureSprintDeep diveMediumDecode Design Add and Search Words Data Structure
- Search Suggestions SystemEssentialsDeep diveMediumDecode Search Suggestions System
- Word Search IISprintDeep diveHardDecode Word Search II
Pattern guide
Trees show up in roughly one interview question in five, and almost all of them reduce to the same small decision: what does each node need to know, and where does that information come from? Get that right and the code is often six lines. Get it wrong and you end up re-walking the tree from every node, which is the O(n²) answer interviewers are waiting for you to avoid.
What it is
A binary tree is a set of nodes where each node has a value and up to two children, left and right. The top node is the root, nodes with no children are leaves, and the height h is the number of levels. A subtree is any node together with everything below it.
The whole pattern rests on one fact: a subtree is itself a tree. So most tree functions are written as "solve it for the left subtree, solve it for the right subtree, combine at this node". The empty tree is the base case. Here is that idea computing the height of a tree, children first, then the node:
Recursion dives to a leaf first. 1 has two empty children, each of height 0, so 1 reports 1.
That order, children before parent, is called postorder. The other two depth-first orders are preorder (node, then children) and inorder (left, node, right). Level order visits the tree top to bottom, one level at a time, using a queue. Which order you pick is most of the solution.
height(node) returns 1 + max(height(left), height(right)). What should it return for an empty node?How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
"root of a binary tree", TreeNode | Recursion on subtrees, base case on the empty node |
| "level", "row", "depth", "left to right", "from the top" | Level-order BFS with a queue |
| "path from the root", "ancestor above it" | Top-down DFS: pass state down as an argument |
| "may or may not pass through the root", "any path" | Bottom-up DFS with a running global best |
| "binary search tree", "BST", "kth smallest" | Use the ordering: go one way, or walk inorder |
| "prefix", "starts with", "autocomplete", "dictionary of words" | A trie |
| "serialize", "construct from traversals", "in place" | Build and reshape: rebuild or rewire nodes |
Constraint clues
| Constraint | What it means |
|---|---|
number of nodes <= 10^4 or 10^5 | O(n) or O(n log n). Re-walking subtrees from every node is O(n²) on a skewed tree |
| Tree is a valid BST | O(h) is possible: you only follow one path |
0 <= number of nodes | The empty tree is a real test case |
-10^9 <= Node.val | Negatives exist: never start a best or a bound at 0 |
Up to 10^5 nodes, could be skewed | Python's default recursion limit is 1000. Consider BFS or an explicit stack |
words.length <= 3 * 10^4 with shared prefixes | Put the words in a trie instead of checking each one |
Input and output shape clues
| Shape | Likely sub-pattern |
|---|---|
| Two trees in, boolean out | Compare and mirror |
| List of lists by level | Level-order BFS |
| A single number about the best path, height or count | Bottom-up DFS (or top-down if it depends on ancestors) |
| A node or subtree out, BST in | BST properties |
| A tree out, lists in (or a string) | Build and reshape |
A class with insert, search, startsWith | Tries |
Looks like it but isn't
- Graphs. Trees are graphs, but without cycles and with a root, so you never need a visited set unless you add parent links (as in All Nodes Distance K). Reach for graph tools only when movement goes up as well as down.
- Binary search. A BST search looks like binary search, but you follow pointers, not indices, and the cost is O(h), not always O(log n). A skewed BST is a linked list.
- Dynamic programming. House Robber III and Maximum Path Sum are DP on a tree, but the recursion already visits each subtree once, so you do not need a memo table. Return a tuple instead.
- Backtracking. If the task is a yes/no or a count, you do not need to build and undo paths. You only need backtracking when you must return the paths themselves.
The sub-patterns
Compare and mirror
When two trees (or two halves of one tree) must be checked against each other, walk them in lockstep: one recursive call takes two nodes. Same Tree pairs left with left; Symmetric Tree pairs left with right. Invert, Subtree of Another Tree and Leaf-Similar Trees live here too.
Pair the root's two children. For a mirror, their values must match (here they do not, which is the point of this picture).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(h) space. Subtree of Another Tree runs this check from every node, so it is O(n · m). Best-known problems: Invert Binary Tree, Same Tree, Symmetric Tree, Subtree of Another Tree.
Top-down DFS
Use this when a node's answer depends on its ancestors: the largest value above it, the sum so far, the direction you arrived from. Pass that state down as an argument. Nothing needs to come back up except a count or a flag.
The root is always good. Pass best = 3 to both children.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(h) space. Path Sum III adds a hash map of running sums, still O(n). Best-known problems: Path Sum, Count Good Nodes in Binary Tree, Path Sum III, Longest ZigZag Path.
Bottom-up DFS
Use this when a node's answer depends on its descendants: heights, sums of subtrees, whether p or q lives below. Each call returns something to its parent (postorder). The twist in the harder problems is that the value you return is not the answer: you return a one-sided fact and update a global best with a two-sided one.
Leaves 4 and 5 return height 1. A path peaking at a leaf has 0 edges.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(h) space. Best-known problems: Maximum Depth, Diameter of Binary Tree, Binary Tree Maximum Path Sum, Lowest Common Ancestor of a Binary Tree, House Robber III.
Maximum Path Sum uses gain(node) = node.val + max(left, right) with each side clamped at 0, and updates best with node.val + left + right. What is the answer for this tree?
# -10 # / \ # 9 20 # / \ # 15 7 # best starts at the root value
Level-order BFS
When the prompt talks about levels, rows, the view from one side, or the shortest distance, use a queue. The trick for level-aware answers: at the start of each round the queue holds exactly one full level, so snapshot its size (or build a fresh list for the next level).
Round 1: the queue holds just the root. Record [3], enqueue 9 and 20.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(w) space where w is the widest level (up to n/2).
Best-known problems: Binary Tree Level Order Traversal, Right Side View, Minimum Depth, All Nodes Distance K.
BST properties
In a binary search tree every node is larger than everything in its left subtree and smaller than everything in its right subtree. Two consequences do all the work: one comparison tells you which side to go (search, insert, delete, LCA), and an inorder walk visits values in sorted order (kth smallest, validation).
6 is less than 8, so it can only be on the left. The whole right side is skipped.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(h) for search, insert, delete and LCA; O(n) for validation; O(h + k) for kth smallest. Best-known problems: Validate Binary Search Tree, Kth Smallest Element in a BST, Lowest Common Ancestor of a BST, Delete Node in a BST.
Build and reshape
Some problems hand you something that is not a tree (two traversal lists, a sorted array, a string) and ask you to build one, or ask you to rewire an existing tree in place. The recipe: find the root first, find what belongs on each side, then recurse on index ranges rather than slicing lists.
Preorder is [3, 9, 20, 15, 7], so 3 is the root. In this inorder list it sits at index 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) when you use a value-to-index map and index ranges; O(n²) if you slice and search lists at every step. Best-known problems: Construct Binary Tree from Preorder and Inorder Traversal, Serialize and Deserialize Binary Tree, Convert Sorted Array to BST, Flatten Binary Tree to Linked List.
Tries
A trie (prefix tree) stores strings one character per level, so words with the same beginning share a path. Each node has a map of children and a flag that marks the end of a word. Any problem about prefixes across many words, or searching a grid for many words at once, wants one.
All four words share the path c then a. A prefix query for ca walks two nodes, however many words are stored.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(L) per insert or lookup for a string of length L, independent of how many words are stored. Space is the total number of characters inserted. Best-known problems: Implement Trie, Design Add and Search Words Data Structure, Word Search II, Search Suggestions System.
A decision checklist
Match each prompt to the sub-pattern that fits it best.
Put the steps of a strong approach to an unfamiliar tree problem in order.
- Tap the steps below in the right order.
Traps
- Forgetting the empty tree.
root.leftonNonecrashes. Start every function with the empty case, and check whether the prompt allows zero nodes. - Treating a missing child as a leaf. In Minimum Depth and Path Sum, a node with one child is not an end point. Check
left is None and right is None, not just "I reached None". - Comparing only with the parent. Validating a BST by checking each node against its children accepts
[5, 4, 6, null, null, 3, 7]. Pass bounds down from all ancestors. - Returning the answer instead of the helper value. In Diameter and Maximum Path Sum, the parent needs a one-sided value, while the answer is two-sided. Keep them separate, with a global best.
- Starting a best at 0. With negative values, the true answer can be negative. Start from the root's value.
- Re-walking subtrees. Calling
height()from every node, or searching a list inside a recursion, quietly turns O(n) into O(n²). - Deep recursion. A skewed tree of 10^4 nodes exceeds Python's default limit of 1000 frames. Use BFS or an explicit stack when depth can be large.
- Tries without an end flag. Inserting "apple" creates the path for "app", but "app" is not a word until it is marked.
Always test: the empty tree, one node, a tree shaped like a list (all left or all right), duplicate values, and negative values.
min_depth(n) = 0 if n is None else 1 + min(min_depth(n.left), min_depth(n.right)). What does it return for [1, 2] (root 1 with a left child 2)?How to talk it through
- Subtree
- A node together with all of its descendants. Every subtree is itself a tree, which is why recursion fits.
- Postorder
- Visit both children before the node. Used when a node's answer depends on its descendants (bottom-up DFS).
- Inorder
- Left subtree, node, right subtree. On a BST it visits values in sorted order.
- Level-order traversal
- Visit nodes top to bottom, left to right, using a queue. One round per level.
- Binary search tree
- Every node is larger than everything on its left and smaller than everything on its right, so search follows one path.
- Trie
- A tree of characters where words with a shared prefix share a path. Each node has children and an end-of-word flag.