Binary tree
easy 18 minA binary tree is a hierarchy of nodes where each node has at most two children, left and right, hanging from a single root.
See it run
Name every part of a tree, sort trees by shape, store one in an array, then walk the same seven nodes in all four orders.
Operations
Anatomy: root, leaf, depth, height
Every word used about trees, pointed at on one 8-node tree: root, parent, child, sibling, leaf, depth, height, subtree and level.
Step 1 of 9
Nodes and edges
n = 8 · edges = 7
A binary tree is a set of nodes where each node holds a value and at most two links, left and right. This one has 8 nodes joined by 7 edges: every node except the top has exactly one edge up to its parent, so a tree with n nodes always has n - 1 edges.
Step 1: Nodes and edges
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left # left child, or None self.right = right # right child, or Nonedef is_leaf(node): return node.left is None and node.right is Nonedef height(node): # edges on the longest path down if node is None: return -1 # empty tree is -1, so a leaf is 0 return 1 + max(height(node.left), height(node.right))def depth(root, target, d=0): # edges from the root down to target if root is None: return -1 if root is target: return d found = depth(root.left, target, d + 1) return found if found != -1 else depth(root.right, target, d + 1)- Time
- O(1) per node
- Space
- O(1) per node
- edges
- n − 1 = 7
- height (edges)
- 3
- leaves
- 4
Say which convention you use. Height in edges gives a leaf 0; LeetCode's maximum depth counts nodes and gives a leaf 1.
In the real world
The same binary tree doing real jobs. Pick one and step through it.
A compiler stores (3 + 4) × 2 as a tree: operators inside, numbers at the leaves. Postorder evaluates it; inorder prints it back.
Step 1 of 4
Operators inside, numbers at the leaves
(3 + 4) × 2
(3 + 4) × 2 becomes a tree with × at the root, + and 2 as its children, and 3 and 4 under +. Brackets are not stored: the shape already says that + happens first.
Step 1: Operators inside, numbers at the leaves
def evaluate(node): if node.left is None: # a leaf holds a number return node.val a = evaluate(node.left) # postorder: both operands first b = evaluate(node.right) return a + b if node.val == "+" else a * bCommon mistakes
The bugs interviewers watch for, with the fix beside each.
No base case for None
criticalEvery recursive tree function reaches empty children. Without a check,
node.lefton None raises AttributeError the first time a leaf is reached.Wrongdef size(node): return 1 + size(node.left) + size(node.right) # crashes at the first leafRightdef size(node): if node is None: return 0 return 1 + size(node.left) + size(node.right)The output line in the wrong place
majorThe three depth-first traversals differ only in where the node is recorded. Putting append before the left call turns inorder into preorder without any error.
Wrongdef inorder(node, out): if node: out.append(node.val) # this is preorder inorder(node.left, out) inorder(node.right, out)Rightdef inorder(node, out): if node: inorder(node.left, out) out.append(node.val) # between the two calls inorder(node.right, out)Mixing height conventions
majorA base case of 0 for None counts nodes; -1 counts edges. Mixing them, for example 0 for None and calling the answer the height in edges, makes every answer one too big.
Wrongdef height(node): # claims edges if node is None: return 0 # but this counts nodes: leaf gives 1 return 1 + max(height(node.left), height(node.right))Rightdef height(node): # edges: leaf 0, empty -1 if node is None: return -1 return 1 + max(height(node.left), height(node.right))Building lists by concatenation
minorinorder(l) + [v] + inorder(r)copies lists at every level, so a skewed tree costs O(n²). Appending to one shared list is O(n).Wrongdef inorder(node): if not node: return [] return inorder(node.left) + [node.val] + inorder(node.right)Rightdef inorder(root): out = [] def walk(node): if node: walk(node.left) out.append(node.val) walk(node.right) walk(root) return outAssuming the tree is balanced
majorA degenerate tree with 100,000 nodes is 100,000 calls deep. Python stops at about 1,000 frames, so recursive code raises RecursionError. Use an explicit stack or queue when the input can be skewed.
Wrongdef size(node): # RecursionError on a long chain if node is None: return 0 return 1 + size(node.left) + size(node.right)Rightdef size(root): count, stack = 0, [root] if root else [] while stack: node = stack.pop() count += 1 stack.extend(c for c in (node.left, node.right) if c) return countLosing the level boundaries in BFS
minorChecking the queue inside one loop mixes levels together. Read len(queue) at the start of each round; exactly that many nodes are the current level.
Wrongwhile queue: node = queue.popleft() level.append(node.val) # which level? no way to tellRightwhile queue: level = [] for _ in range(len(queue)): # this level only node = queue.popleft() level.append(node.val) queue.extend(c for c in (node.left, node.right) if c) out.append(level)
Interview tips
How to explain it
- A binary tree is a hierarchy where each node has at most two children, left and right, starting from one root.
- Traversals are O(n) time and O(h) space; h is about log n when balanced and n when skewed.
- Inorder sorts a BST, preorder copies or serialises, postorder deletes or aggregates, level order works level by level.
Spot it in problems
- You need something from both children first (height, size, diameter, balanced?): postorder recursion.
- The question says level, row, nearest or shallowest: BFS with a queue.
- Root-to-leaf paths or path sums: preorder with a path you add to and undo (backtracking).
- Rebuild a tree from two traversals: preorder or postorder gives the root, inorder splits left from right.
Memory tricks
- The name says where the node goes: PRE = before both children, IN = in between, POST = after both.
- LNR, NLR, LRN: left always comes before right; only N moves.
- Cave story: preorder plants a flag on entering a room, inorder marks it between the left and right tunnels, postorder marks it on the way out.
Watch out
- Ask first: binary tree or binary search tree? Can values repeat? Can the tree be empty?
- Test with None, a single node and a skewed chain.
- Recursion is O(h) stack, which is O(n) on a skewed tree.
- Root depth is 0; some texts number the root as level 1. Say which.