Courses / DSA Patterns for Working Engineers / Chapter 21
Module 7 · Trees and tries · Chapter 21 of 39
Tree Depth-First Search: Recursion That Returns Answers Upward
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Tree Breadth-First Search: Level by Level.
Part 1 · Introduction to tree depth-first search
Trees, nodes and subtrees
A folder structure, an org chart and an arithmetic formula are all trees. Searching one depth first means a recursive function that handles a node and then calls itself on each of its subtrees.
A binary tree is a set of nodes where each node has at most two children, called left and right, and exactly one node, the root, has no parent. A node with no children is a leaf. Every node is the root of its own subtree, which is that node and everything below it. The depth of a node is the number of edges from the root down to it, and the height of the tree is the depth of its deepest leaf. Some problems count nodes on a path instead of edges, so a lone node has height 0 by edges and 1 by nodes; each lesson says which it uses. An empty tree is written null.
Code blocks follow the convention set out in the first chapter.
export class TreeNode { val: number left: TreeNode | null right: TreeNode | null constructor( val: number, left: TreeNode | null = null, right: TreeNode | null = null, ) { this.val = val this.left = left this.right = right } }
tree.ts: a node with a value and two children
Writing trees as nested constructor calls gets tiresome, so the chapter builds them from a level-order list: values row by row from the top, left to right, with null for a missing child. Children of a missing node are not listed, and entries that no node has a place for are ignored. The helper reads the list with a queue, as in the graphs chapter.