Find Distance in a Binary Tree Problem
#1740
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1740.
Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.
The distance between two nodes is the number of edges on the path from one to the other.
Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
Output: 3
Explanation: There are 3 edges between 5 and 0: 5-3-1-0.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
Output: 2
Explanation: There are 2 edges between 5 and 7: 5-2-7.
Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
Output: 0
Explanation: The distance between a node and itself is 0.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^9- All
Node.valare unique. pandqare values in the tree.
Solution
Approach: Lowest Common Ancestor, Then Two Depths
The shortest path between two nodes in a tree goes up to their lowest common ancestor (LCA) and back down, so the distance is the depth of p below the LCA plus the depth of q below the LCA.
- Find the LCA recursively: return the node itself if it holds
porq; otherwise look in both subtrees. If both sides return something, this node is the LCA; if only one does, pass that result up. - From the LCA, run a DFS that returns the number of edges down to the node with a given value (or
-1if it is not in that subtree). Do it once forpand once forq, and add the two results.
If p == q, the LCA is that node and the answer is 0.
Complexity: O(n) time and O(h) extra space for the recursion, where h is the height of the tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDistance(self, root: Optional[TreeNode], p: int, q: int) -> int:
def lca(root, p, q):
if root is None or root.val in [p, q]:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left is None:
return right
if right is None:
return left
return root
def dfs(root, v):
if root is None:
return -1
if root.val == v:
return 0
left, right = dfs(root.left, v), dfs(root.right, v)
if left == right == -1:
return -1
return 1 + max(left, right)
g = lca(root, p, q)
return dfs(g, p) + dfs(g, q)