Looking for fast algorithm to find distance between two nodes in binary tree

cboettig picture cboettig · Jan 25, 2010 · Viewed 25.5k times · Source

How do I find the distance between two nodes in a binary tree? Equivalently, what algorithms are there for finding the most recent common ancestor (lowest common ancestor) of two nodes?

Answer

Javier picture Javier · Jan 25, 2010
  1. calculate the list of ancestors for each node
  2. find the common prefix
  3. the last element from the common prefix is the lowest common ancestor
  4. remove the common prefix from both ancestor lists
  5. the distance is the sum of lengths of the remaining lists +1