The Closest Leaf in a Binary Tree interview question asks you to find the leaf node that is closest to a given target node k. A leaf node is defined as a node with no children. The "distance" is the number of edges in the shortest path between the target node and the leaf. This is tricky because the closest leaf might be in the target node's own subtree, or it might be reachable by going up through a parent and then down into a different subtree.
Databricks, LinkedIn, and Amazon use this Tree interview pattern to test your ability to convert a tree into a graph. Trees are directed (parent to child), but finding the "closest" node often requires moving in any direction (including child to parent). It tests your knowledge of Breadth-First Search (BFS) and tree-to-graph transformation.
The standard approach is a two-step process:
k, perform a BFS. The first leaf node you encounter in the BFS will be the closest one.Consider a tree where:
1 is the root.1 has children 2 and 3.2 has child 4 (leaf).3 has children 5 and 6 (leaves).
Target node: 3.3 is connected to 1 (parent), 5 (child), and 6 (child).3.5 and 6. Both are leaves!5 or 6.
If the leaf 4 was closer through the parent 1, the BFS would have found it if it reached that level first.visited set in BFS after converting the tree to an undirected graph, leading to infinite cycles.k is not present in the tree (though usually guaranteed to exist).Whenever you need to find the "shortest path" in a tree that allows moving to parents, immediately think of BFS on an undirected graph representation of the tree.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Largest Value in Each Tree Row | Medium | Solve | |
| Maximum Level Sum of a Binary Tree | Medium | Solve | |
| Deepest Leaves Sum | Medium | Solve | |
| Print Binary Tree | Medium | Solve | |
| Sum of Nodes with Even-Valued Grandparent | Medium | Solve |