TRT
Sign in

Core · Module 10 · Lesson 4 of 5

Tree recursion patterns

Most tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.

Pro — members onlyAbout 14 minutes

By the end you can

  • Solve problems bottom-up by combining the answers of the two subtrees
  • Solve problems top-down by passing information from the root toward the leaves
  • Return one value while tracking another, as in the diameter and maximum path sum

Builds on Insert and delete.

01 · A question first

The diameter of a tree is the longest path between any two of its nodes, and it doesn't have to pass through the root. A function that only computes the height of each subtree can still find it in a single pass. How?

Make a guess before you read on.

02 · The idea

Members only

Unlock the full lesson

This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.

What's inside

  • One function, one subtree
  • Shape 1: bottom-up
  • Shape 2: top-down
  • Shape 3: return one thing, record another
  • Returning a node: the lowest common ancestor
  • Working with two trees at once
  • Choosing the shape
  • Pseudocode & Multi-Language Implementations (C++, Java, Python)

03 · Practice

Something wrong with this lesson? Report a problem