Unicorns Interview Coding Question: Find the Distance Between Two Nodes in a Binary Tree

15 Views
No Comments

Find the distance between two nodes in a binary tree. The distance between two nodes is defined as the minimum number of edges to be traversed to reach one node from another.

Example:

        1
      /   \
     2     3
    / \   / \
   4   5 6   7
          \
           8
Dist(4, 5) = 2
Dist(4, 6) = 4
Dist(4, 3) = 3
Dist(4, 8) = 5

This problem asks for the minimum number of edges between two nodes in a binary tree. A common solution is to find the lowest common ancestor (LCA) of the two nodes, then add the distances from each node to that ancestor. Another way is a depth-first search that locates the targets and combines path lengths while backtracking. The examples illustrate how the path can move up to the LCA and then down to the other node.

END
 0