The Find Distance in a Binary Tree interview question asks you to find the number of edges on the path between two given nodes and in a binary tree. You are given the values of the two nodes, and you are guaranteed that both exist in the tree.
Amazon and other companies use this "Medium" problem to test your understanding of the Lowest Common Ancestor (LCA) interview pattern. The distance between any two nodes in a tree is defined by their relationship to their common ancestor. It evaluation your proficiency with Depth-First Search (DFS) and your ability to combine results from multiple recursive calls.
This problem uses the Lowest Common Ancestor (LCA) pattern.
The distance between nodes and is calculated as:
dist(Root, P) + dist(Root, Q) - 2 * dist(Root, LCA(P, Q))
Tree:
3
/
5 1
/
6 2
Find distance between 6 and 1.
LCA is a fundamental building block. Once you find the LCA, any "path property" (distance, sum, max value) can be calculated by looking at the two paths from the LCA to the target nodes. Master the LCA recursive algorithm.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Clone Binary Tree With Random Pointer | Medium | Solve | |
| Cousins in Binary Tree II | Medium | Solve | |
| Lowest Common Ancestor of Deepest Leaves | Medium | Solve | |
| Amount of Time for Binary Tree to Be Infected | Medium | Solve | |
| All Nodes Distance K in Binary Tree | Medium | Solve |