AlgoFrames

Recursive problems on trees: height, size, mirror, paths

Height, size, mirror images and path sums all follow one pattern: solve both subtrees, then combine at the node. Watch values bubble up to the root.

Before you start: Level-order traversal.

The idea

How tall is this tree? Node 1 cannot see the whole tree, but it can ask its two children.

Height, size, sums, mirror images and path checks all work this way. Each node asks its subtrees, waits for their answers and combines them.

Intuition

Node 2 waits until both children report. Each says height 1, so node 2 reports 1 + max(1, 1) = 2.

An empty child reports 0. That is the base case, and it makes every leaf report 1 + max(0, 0) = 1.

Every problem here has one shape: solve the left subtree, solve the right subtree, then combine at the node.

Only the combine line changes. Height uses 1 + max(l, r), size uses 1 + l + r, and a sum uses node.val + l + r.

Complexity

Time is O(n): each node gets one call and does constant work. Space is O(h), one stack frame per level of the current path.

The combine step only adds or compares two numbers. The stack holds the frames from the root down to the current node.

A chain of n nodes keeps n frames on the stack at once. A balanced tree needs only about log n.

A chain of 100,000 nodes can overflow the call stack. Then use an explicit stack or a level-order loop.

Pitfalls

Return 0 for an empty node, not 1. With 1, the leaves 4 and 5 report 2, and the tree 2, 4, 5 comes out one too tall.

Some problems count height in edges instead of nodes. Then a leaf has height 0. Check which one the problem asks for.

A new tree: 1 with one child, 2, and target 1. A path must end at a leaf, so node 1 alone is not an answer.

Test for a leaf with node.left = null and node.right = null. Returning true at any empty child accepts paths that stop halfway.

Variations

Invert a tree: invert both subtrees, then swap them. The result is the mirror image of the original.

The work at each node is one swap. The recursion takes care of every subtree below it.

A new tree, 1 to 5. Diameter returns a height upward but records the best path, which bends where left plus right height is largest.

Code

Pseudocode

height(node)
  if node = null: return 0
  l ← height(node.left)
  r ← height(node.right)
  return 1 + max(l, r)

Python

def height(node):
    if node is None:
        return 0
    l = height(node.left)
    r = height(node.right)
    return 1 + max(l, r)

JavaScript

function height(node) {
  if (node === null) return 0;
  const l = height(node.left);
  const r = height(node.right);
  return 1 + Math.max(l, r);
}

Java

int height(TreeNode node) {
  if (node == null) return 0;
  int l = height(node.left);
  int r = height(node.right);
  return 1 + Math.max(l, r);
}

Cost at a glance

TimeO(n)
SpaceO(h)
InputBinary tree
OutputOne value combined from both subtrees

Practice problems (8)

Who reports first? Warm-up

height runs on this tree, left child first. A node reports its height only after both children have reported. Click the first node to report, then put all nodes in the order they report.

Complete the node counter Warm-up

Fill the two blanks so countNodes returns the number of nodes in a binary tree.

Max depth Standard

Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.

Invert a tree Standard

Given the root of a binary tree, invert it: swap the left and right child of every node, so the tree becomes its mirror image. Return the root of the inverted tree.

Path sum Standard

Given the root of a binary tree and an integer targetSum, return true when some path from the root down to a leaf has values that add up to targetSum. A leaf is a node with no children.

Same tree Standard

Given the roots p and q of two binary trees, return true when they are the same tree: the same shape, with equal values in every position.

Fix the height function Standard

This function should return the number of nodes on the longest root-to-leaf path. It returns a wrong answer for every tree. Click the line with the bug.

Diameter of a tree Challenge

Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. The path does not have to pass through the root. An empty tree or a single node has diameter 0.

Related topics

Next on the path: Serialization and construction