Binary Trees

What a binary tree is, the recursive pattern that solves most tree problems, how tree shape affects cost, and the follow-up questions interviewers ask.

17 minLesson 1 of 6
On this page
  1. Terms used for trees
  2. How the recursive pattern works
  3. Tracing the height by hand
  4. Code for height and node count
  5. Time and space
  6. Kinds of binary trees
  7. When this pattern does not fit
  8. Passing information down the tree
  9. Pitfalls
  10. In the interview
  11. What to practise next

A binary tree is a structure made of nodes, where each node holds a value and has at most two children, called left and right. It stores data that branches, such as an expression, a hierarchy or a decision process, and it is the base of the search trees and heaps covered later. Almost every problem about a binary tree can be solved with one recursive pattern: ask the same question of each child, then combine the two answers with the current node.

Without that pattern you would have to keep track by hand of which nodes you have visited and which are still waiting, because a tree has no single next element the way an array does. The pattern lets the call stack keep that bookkeeping for you.

Terms used for trees

  • The root is the single node at the top.
  • A leaf is a node with no children.
  • A subtree is any node together with everything below it.
  • The depth of a node is the number of steps from the root to it. The root has depth 0.
  • The height of a tree is the number of nodes on its longest path from the root down to a leaf. An empty tree has height 0.
left subtree 6 2 9 4 7 1 root leaf leaf depth 0 depth 1 depth 2 depth 3
A binary tree with 6 nodes and height 4. The dashed box marks the left subtree of the root.

In code, a node is an object with val, left and right fields. A missing child is null in JavaScript or None in Python. A node is like a linked list node that has two next pointers instead of one.

How the recursive pattern works

A binary tree is either empty, or it is a node with a left tree and a right tree attached to it. The children are smaller trees of the same kind, which is why recursion fits. A recursive tree function has three parts:

  1. The base case handles the empty tree and returns the obvious answer, such as 0 for the height, the node count or the sum.
  2. The function calls itself on the left child and on the right child.
  3. The function combines the two answers with the current node and returns the result.

For the height, the combining step is that the height of a tree is the larger of its two subtree heights, plus 1 for the current node.

Tracing the height by hand

A node cannot return until both of its children have returned, so the answers are produced from the bottom of the tree upward. Green nodes are finished.

Compute the height of the treeUse the arrows or ← → keys
height(node):  if node is empty: return 0  left = height(node.left)  right = height(node.right)  return 1 + max(left, right)
  1. 629471

    1height(6) cannot answer yet, so it asks its left child, 2.

  2. 629471

    2height(2) cannot answer yet either, so it asks its left child, 4.

  3. 629471

    3height(4) asks its empty left child, which returns 0 at once. Then it asks its right child, 1.

  4. 629471
    h(1)
    1

    41 is a leaf. Both of its children return 0, so it returns 1 + max(0, 0) = 1.

  5. 629471
    h(1)
    1
    h(4)
    2

    5Back at 4, the left answer is 0 and the right answer is 1, so it returns 1 + max(0, 1) = 2.

  6. 629471
    h(1)
    1
    h(4)
    2
    h(2)
    3

    6Back at 2, the left answer is 2 and the right child is empty (0), so it returns 1 + max(2, 0) = 3.

  7. 629471
    h(1)
    1
    h(4)
    2
    h(2)
    3

    7Now the root asks its right child, 9. The left child of 9 is empty (0), so 9 asks its right child, 7.

  8. 629471
    h(1)
    1
    h(4)
    2
    h(2)
    3
    h(7)
    1

    87 is a leaf, so it returns 1 + max(0, 0) = 1.

  9. 629471
    h(1)
    1
    h(4)
    2
    h(2)
    3
    h(7)
    1
    h(9)
    2

    9Back at 9, the left answer is 0 and the right answer is 1, so it returns 1 + max(0, 1) = 2.

  10. 629471
    h(2)
    3
    h(9)
    2
    h(6)
    4
    nodes visited
    6

    10Back at the root, the answers are 3 and 2, so it returns 1 + max(3, 2) = 4. Each of the 6 nodes was visited once.

1 / 10

Code for height and node count

The two functions have the same structure, and only the combining line is different.

class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}
 
// Number of nodes on the longest path down from node.
function height(node) {
  if (node === null) return 0; // empty tree
  return 1 + Math.max(height(node.left), height(node.right));
}
 
function countNodes(node) {
  if (node === null) return 0;
  return 1 + countNodes(node.left) + countNodes(node.right);
}
 
// The tree from the trace.
const root = new TreeNode(6,
  new TreeNode(2, new TreeNode(4, null, new TreeNode(1))),
  new TreeNode(9, null, new TreeNode(7)));
height(root);     // 4
countNodes(root); // 6
class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
 
# Number of nodes on the longest path down from node.
def height(node):
    if node is None:  # empty tree
        return 0
    return 1 + max(height(node.left), height(node.right))
 
def count_nodes(node):
    if node is None:
        return 0
    return 1 + count_nodes(node.left) + count_nodes(node.right)
 
# The tree from the trace.
root = TreeNode(6,
    TreeNode(2, TreeNode(4, None, TreeNode(1))),
    TreeNode(9, None, TreeNode(7)))
height(root)       # 4
count_nodes(root)  # 6
Try it: Count the leaves

Write countLeaves(node) using the same three moves. What does it return for the tree in the figure?

Show a sample answer
function countLeaves(node) {
  if (node === null) return 0;
  if (node.left === null && node.right === null) return 1; // a leaf
  return countLeaves(node.left) + countLeaves(node.right);
}
def count_leaves(node):
    if node is None:
        return 0
    if node.left is None and node.right is None:  # a leaf
        return 1
    return count_leaves(node.left) + count_leaves(node.right)

It returns 2, because the leaves are 1 and 7. A leaf needs its own case, because both of its children return 0 and the sum of those would be 0. The last line does not add 1 for the current node, because only leaves are counted.

Time and space

Each function does a constant amount of work for every node, so the time is O(n).

The space depends on the shape of the tree. A call that is waiting for its children stays on the call stack, so the stack grows as deep as the height h of the tree, and the height depends on how the nodes are arranged.

4 2 6 1 3 5 7 height 3 1 2 3 4 5 6 7 height 7
The same 7 values in two shapes. The balanced tree has height 3 and the chain has height 7.

In a balanced tree each level holds about twice as many nodes as the level above, so a million nodes fit in about 20 levels and the height is about log₂ n. In a chain the height is n. Recursive functions on trees therefore use O(h) stack space, and the search trees in later lessons take O(h) time per operation.

TimeO(n)
SpaceO(h)

Every node is visited once, and the stack holds one call per level. The height h is between about log₂ n for a balanced tree and n for a chain.

Kinds of binary trees

Several names describe the shape of a tree. They matter because the cost of many operations depends on the height, and because interview problems state the shape as a guarantee you can use.

Full and perfect trees

In a full binary tree every node has either 0 or 2 children, and no node has exactly one. In a perfect binary tree, every leaf is at the same depth and every other node has 2 children, so a perfect tree with height h has 2h - 1 nodes. A perfect tree is the best possible shape, because it holds the most nodes for a given height.

Complete trees

In a complete binary tree every level is full except possibly the last, and the last level is filled from the left. Because there are no gaps, a complete tree can be stored in an array with the children of index i at 2i + 1 and 2i + 2. This is how a heap is stored, and the tracer in this lesson uses the same layout for its pictures.

Balanced trees

A tree is height-balanced if, at every node, the heights of the left and right subtrees differ by at most 1. This keeps the height close to log₂ n. Many problems say "balanced" and then expect O(log n) work per operation, so check whether the statement means this definition.

Degenerate trees

A degenerate tree is one where every node has at most one child, so it is really a linked list and its height is n. Test data often includes one, and it is the case in which recursion can overflow the stack.

Binary search trees

A binary search tree is a binary tree that also keeps its values in order: everything in the left subtree of a node is smaller than the node, and everything in the right subtree is larger. A plain binary tree has no such rule, so you cannot skip any part of it when searching. Binary Search Trees covers how that rule makes searching fast.

When this pattern does not fit

Level-by-level questions, such as "return the nodes at each depth", do not fit the pattern well, because the answer is grouped across subtrees instead of being built from each subtree's own answer. Use a queue and a breadth-first traversal for those, as described in Tree Traversals. A very deep tree needs an explicit stack in place of recursion, as the pitfalls below explain.

Passing information down the tree

In the pattern above, information flows upward: each call returns an answer to its parent. Some problems need information to flow downward instead, and then the function takes an extra parameter that the parent fills in for each child. For example, to check whether any root-to-leaf path adds up to a target, each call receives the target minus the values of the nodes above it, and a leaf checks whether that remainder equals its own value. A function that must know a node's depth, or the allowed range of values for a node, works the same way.

Pitfalls

In the interview

A problem is probably a tree recursion problem when its input is a node of a tree and it asks for a single value about the whole tree, such as a depth, a count, a sum, whether a property holds everywhere, or the best path. If the answer for a node can be worked out from the answers for its two children, write the three-part recursive function. If the question asks about levels, use a queue instead.

Interviewers usually start with a simple question, such as the depth of the tree, and then change it to see whether you can adapt the pattern. Questions to expect:

  • "What is the time and space complexity?" The time is O(n), because every node is visited once. The space is O(h) for the call stack, where h is the height, which is O(log n) for a balanced tree and O(n) for a chain. Give both cases, because the interviewer is checking that you know the shape matters.
  • "What happens on a tree with a million nodes in a chain?" The recursion is a million calls deep and overflows the stack. The fix is an iterative version with an explicit stack, which does the same work but keeps its stack on the heap, where its size is limited only by memory.
  • "Check whether the tree is balanced." The direct approach calls height on both children at every node, which is O(n²) on a chain because the same nodes are measured again and again. A better approach returns the height from each call and returns a marker such as -1 when a subtree is unbalanced, so each node is visited once and the time is O(n).
  • "Find the diameter, the longest path between any two nodes." The longest path through a node has a length (in edges) of its left height plus its right height. The answer is the maximum of that value over all nodes, so the function returns the height as usual and updates a running maximum on the side. This is the standard example of a function that returns one value and records another.
  • "Find the lowest common ancestor of two nodes." Return the node itself if it is one of the two targets, or if the recursive calls on the left and on the right both find a target. Otherwise return whichever side found something. The first node where both sides report a hit is the answer. The time is O(n) and the space is O(h).
  • "What is the difference between a binary tree and a binary search tree?" A binary search tree keeps the left subtree smaller and the right subtree larger at every node, so a search can discard half of a balanced tree at each step. A plain binary tree has no ordering, so a search must check every node.
Quick check

Using this lesson's definition, what is the height of a tree that is a single node with no children?

You want the sum of all values in a tree. After handling the empty tree, what should the combining line return?

A tree of 50,000 nodes is a chain in which every node has only a right child. What happens when you run the recursive height on it?

An interviewer asks whether a tree is height-balanced. Why is calling height on both children at every node a weak solution?

What to practise next

Height visits the children of a node before the node itself. Tree Traversals covers every useful visiting order, including level by level and walking a tree without recursion, and Binary Search Trees adds the ordering rule that makes search fast.