Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 223
cboettig Avatar asked Jan 25 '10 18:01

cboettig


People also ask

How do you find the distance between two nodes in a binary tree?

The distance between two nodes can be obtained in terms of lowest common ancestor. Following is the formula. Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca) 'n1' and 'n2' are the two given keys 'root' is root of given Binary Tree.

What is the distance between two nodes?

The distance between two nodes is defined as the total number of edges in the shortest path from one node to other. For example, consider the binary tree. The distance between node 7 and node 6 is 3. This problem is a standard application of the lowest common ancestor of given nodes.


1 Answers

  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
like image 153
Javier Avatar answered Oct 16 '22 01:10

Javier