Skip to content

Trees

Reach for it when the problem says

  • Hierarchies
  • depth
  • paths
  • BST ordering
Solved
0/39Solved
Problems
39Problems
Variants
7Variants

Problems

7 variants

Compare and mirror

0 of 5 solved

Bottom-up DFS

0 of 6 solved

Level-order BFS

0 of 7 solved

BST properties

0 of 6 solved

Top-down DFS

0 of 5 solved

Build and reshape

0 of 6 solved

Tries

0 of 4 solved

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:

Height, computed bottom-up
123479

Recursion dives to a leaf first. 1 has two empty children, each of height 0, so 1 reports 1.

1/5

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.

Quick check
A recursive height(node) returns 1 + max(height(left), height(right)). What should it return for an empty node?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"root of a binary tree", TreeNodeRecursion 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

ConstraintWhat it means
number of nodes <= 10^4 or 10^5O(n) or O(n log n). Re-walking subtrees from every node is O(n²) on a skewed tree
Tree is a valid BSTO(h) is possible: you only follow one path
0 <= number of nodesThe empty tree is a real test case
-10^9 <= Node.valNegatives exist: never start a best or a bound at 0
Up to 10^5 nodes, could be skewedPython's default recursion limit is 1000. Consider BFS or an explicit stack
words.length <= 3 * 10^4 with shared prefixesPut the words in a trie instead of checking each one

Input and output shape clues

ShapeLikely sub-pattern
Two trees in, boolean outCompare and mirror
List of lists by levelLevel-order BFS
A single number about the best path, height or countBottom-up DFS (or top-down if it depends on ancestors)
A node or subtree out, BST inBST properties
A tree out, lists in (or a string)Build and reshape
A class with insert, search, startsWithTries

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.
Quick check
The prompt says: return, for each depth of the tree, the largest value at that depth. Which sub-pattern fits most directly?
Need a nudge? A hint rules out a wrong answer.

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.

Symmetric: compare outer with outer, inner with inner
3241657

Pair the root's two children. For a mirror, their values must match (here they do not, which is the point of this picture).

1/3
Python
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def mirror(a, b): if a is None or b is None: return a is b # both empty is a match, one empty is not return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left) root = T(1, T(2, T(3), T(4)), T(2, T(4), T(3)))print(mirror(root.left, root.right)) # True
Output
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.

Count good nodes: carry the max so far
313145

result: best = 3, good = 1

The root is always good. Pass best = 3 to both children.

1/4
Python
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def good_nodes(node, best): if node is None: return 0 good = 1 if node.val >= best else 0 best = max(best, node.val) return good + good_nodes(node.left, best) + good_nodes(node.right, best) root = T(3, T(1, T(3)), T(4, T(1), T(5)))print(good_nodes(root, root.val)) # 4
Output
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.

Diameter: return height, record left + right
42513

result: best = 0

Leaves 4 and 5 return height 1. A path peaking at a leaf has 0 edges.

1/3
Python
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def diameter(root): best = 0 def height(node): nonlocal best if node is None: return 0 left, right = height(node.left), height(node.right) best = max(best, left + right) # two-sided: the candidate answer return 1 + max(left, right) # one-sided: what the parent can use height(root) return best print(diameter(T(1, T(2, T(4), T(5)), T(3)))) # 3
Output
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.

Predict the outputPython

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
Need a nudge? Hints walk you through it.

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).

One level per round
9315207

result: [[3]]

Round 1: the queue holds just the root. Record [3], enqueue 9 and 20.

1/3
Python
from collections import deque class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def level_order(root): if root is None: return [] levels, queue = [], deque([root]) while queue: level = [] for _ in range(len(queue)): # exactly one level 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 print(level_order(T(3, T(9), T(20, T(15), T(7)))))
Output
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).

Search for 6: one path, not the whole tree
1346781014

6 is less than 8, so it can only be on the left. The whole right side is skipped.

1/3
Python
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def is_valid_bst(node, low=float("-inf"), high=float("inf")): if node is None: return True if not low < node.val < high: return False return is_valid_bst(node.left, low, node.val) and is_valid_bst(node.right, node.val, high) good = T(5, T(3, T(1), T(4)), T(8))bad = T(5, T(4), T(6, T(3), T(7))) # 3 is under 6 but also right of 5print(is_valid_bst(good), is_valid_bst(bad))
Output
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 gives the root, inorder gives the split
9
0
3
1
15
2
20
3
7
4

Preorder is [3, 9, 20, 15, 7], so 3 is the root. In this inorder list it sits at index 1.

1/3
Python
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def sorted_to_bst(nums, low, high): if low > high: return None mid = (low + high) // 2 return T(nums[mid], sorted_to_bst(nums, low, mid - 1), sorted_to_bst(nums, mid + 1, high)) def inorder(node): return inorder(node.left) + [node.val] + inorder(node.right) if node else [] nums = [-10, -3, 0, 5, 9]root = sorted_to_bst(nums, 0, len(nums) - 1)print(root.val, inorder(root))
Output
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.

Trie holding car, card, care, cat
rootdend of cardeend of carerend of cartend of catacroot

All four words share the path c then a. A prefix query for ca walks two nodes, however many words are stored.

1/2
Python
class TrieNode: def __init__(self): self.children = {} self.is_word = False def insert(root, word): node = root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_word = True def walk(root, text): node = root for ch in text: node = node.children.get(ch) if node is None: return None return node root = TrieNode()for w in ["car", "card", "care", "cat"]: insert(root, w)print(walk(root, "ca") is not None, walk(root, "ca").is_word, walk(root, "car").is_word)
Output
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 the pairs0/6 matched

Match each prompt to the sub-pattern that fits it best.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of a strong approach to an unfamiliar tree problem in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Traps

  • Forgetting the empty tree. root.left on None crashes. 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.

Quick check
A learner writes 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)?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
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.