Problem Description
Given the root of a binary tree and two integers p and q (which are values guaranteed to exist in the tree), return the distance between the nodes with value p and value q. The distance is defined as the number of edges along the path connecting the two nodes. If p equals q, the distance is 0.
Key Insights
- The problem can be effectively solved by first finding the Lowest Common Ancestor (LCA) of the two nodes.
- Once the LCA is located, the distance between the two nodes is the sum of the distance from the LCA to p and from the LCA to q.
- Depth-first search (DFS) is used both to find the LCA and to compute the distance from the LCA to each node.
Space and Time Complexity
Time Complexity: O(n) in the worst-case, where n is the number of nodes in the tree. Space Complexity: O(h), where h is the height of the tree (due to recursion stack).
Solution
We first determine the Lowest Common Ancestor (LCA) of the nodes with values p and q. To do this, we recursively check the left and right subtrees until we find either p or q. Once the LCA is found, we perform a DFS from the LCA to calculate the distance (number of edges) to each target value. The final distance between p and q is the sum of these two distances. Edge cases such as p == q are handled by simply returning a distance of 0.