Trees
Binary trees and binary search trees: the recursive contract, the four traversal orders, BST ranges and lowest common ancestor, each traced on a small tree.
Overview
A tree is a set of nodes joined by edges, with one node at the top (the root) and exactly one path from the root to every other node. There are no cycles. A binary tree is a tree where each node has at most two children, called left and right. Most tree problems use binary trees.
Nearly every tree problem is solved the same way: decide what a call on one node should return, get that answer from the left and right subtrees, and combine the two. If you can state that contract out loud, the code is short. This chapter first names the parts of a tree, then builds the contract on one small example and uses it for traversals, binary search trees and the lowest common ancestor.
Each section below follows the same shape: the rule first, then the rule on a small tree, then the trap to avoid.
The words you need
The rule: five words describe the parts of any tree. The examples in this chapter all use the same seven-node tree, drawn below; it is also a binary search tree, which a later section uses.
- Root: the one node with no parent. Here it is 4.
- Leaf: a node with no children. Here the leaves are 1, 3, 5 and 7.
- Subtree: a node plus everything below it. Node 2 with 1 and 3 is one subtree.
- Depth of a node: the number of edges from the root down to it. The depth of 3 is 2.
- Height of the tree: the number of edges on the longest root-to-leaf path. This tree has height 2.
> [!WARNING] > Some problems count nodes instead of edges. LeetCode's Maximum Depth counts nodes, so its answer for this tree is 3. Check which one the problem means.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio