The Number of Good Leaf Nodes Pairs problem gives you a binary tree and an integer distance. A pair of leaf nodes is "good" if the shortest path between them (through the tree) has length ≤ distance. Count all good leaf node pairs. This coding problem uses DFS that returns distance distributions from each subtree's leaves.
ByteDance, TikTok, and Google ask this because it requires a post-order DFS where each node collects distance distributions from its left and right subtrees, then merges them to count pairs. The DFS, binary tree, and tree interview pattern is the core, and the distance distribution propagation is the key technique.
Post-order DFS with distance list return. For each node, the DFS returns a list of distances from the current node to all leaf nodes in its subtree. For each pair (left_dist, right_dist) where left_dist + right_dist ≤ distance, count one good pair. Return the incremented distance list to the parent (add 1 to each returned distance, pruning those > distance).
Tree: root→(left→(leaf1, leaf2), right→leaf3). distance=3.
Tree problems where you count pairs satisfying a path-length constraint use the "LCA counting" pattern: count at each internal node the pairs whose path goes through this node (one leaf in left subtree, one in right). The DFS returns a list of leaf-to-node distances. Merging two lists with a pair-count step is O(distance²) per node but bounded by the distance parameter. Practice "count leaf pairs within distance d" and "diameter of binary tree" — they use the same distribute-and-merge pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Delete Leaves With a Given Value | Medium | Solve | |
| Binary Tree Longest Consecutive Sequence | Medium | Solve | |
| Change the Root of a Binary Tree | Medium | Solve | |
| Binary Tree Coloring Game | Medium | Solve | |
| Binary Tree Longest Consecutive Sequence II | Medium | Solve |