Find Distance in a Binary Tree - Problem

Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and q in the tree.

The distance between two nodes is the number of edges on the path from one to the other.

Note: You can assume that both values p and q exist in the tree and all node values are unique.

Input & Output

Example 1 — Basic Distance
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 2
💡 Note: The path from node 5 to node 1 is: 5 → 3 → 1, which has 2 edges. So the distance is 2.
Example 2 — Same Subtree
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 2
💡 Note: The path from node 5 to node 4 is: 5 → 2 → 4, which has 2 edges. So the distance is 2.
Example 3 — Adjacent Nodes
$ Input: root = [1,2,3], p = 2, q = 3
Output: 2
💡 Note: The path from node 2 to node 3 is: 2 → 1 → 3, which has 2 edges. So the distance is 2.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 0 ≤ Node.val ≤ 104
  • All Node.val are unique
  • p ≠ q
  • p and q exist in the tree

Visualization

Tap to expand
Find Distance in a Binary Tree INPUT 3 5 p 1 q 6 2 0 8 7 4 p = 5, q = 1 Find edges between p and q ALGORITHM STEPS 1 Find LCA Find Lowest Common Ancestor of p and q 2 LCA = Node 3 Root is ancestor of both 5 and 1 3 Calculate Depths depth(3,5) = 1 depth(3,1) = 1 4 Sum Distances distance = d1 + d2 = 1 + 1 = 2 5 3 LCA 1 Path: 5 -- 3 -- 1 FINAL RESULT 1 1 3 5 1 6 2 0 8 Distance = 2 1 + 1 = 2 edges OK - Output: 2 Key Insight: The distance between two nodes = depth(LCA to p) + depth(LCA to q). Finding LCA first reduces the problem to two simple depth calculations using DFS. Time: O(n) | Space: O(h) where h = tree height TutorialsPoint - Find Distance in a Binary Tree | DFS with LCA Finding
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
31.2K Views
Medium Frequency
~25 min Avg. Time
875 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen