views:

118

answers:

3

I am looking for an algorithm that could find the two most distant elements in a binary tree, not looking for any special language, just for the algorithm.

Thanks.

+8  A: 

Its called diameter of tree.

int diameter(Tree * t) // post: return diameter of t 
{ 
     if (t == 0) return 0; 
     int lheight = height(tree->left); 
     int rheight = height(tree->right);
     int ldiameter = diameter(tree->left); 
     int rdiameter = diameter(tree->right); 
     return max(lheight + rheight + 1, max(ldiameter,rdiameter));
 } 

alt text

copied code and images from here.

TheMachineCharmer
+1 for good algorithm sample taking benefit of tree structure. Although, you'll also need to save the vertices you get distance for and the deepest vertices for the height.
Li0liQ
@Li0liQ: Yes in the end we want names of the vertices that are farthest from each other. I ll add that ASAP. Thanks.
TheMachineCharmer
I a sorry I wrote that I needed the nodes but I just needed the distance :) thanks for this great explanation, I didn't know this "diameter" thing, it will come on handy I hope.
attwad
I will still add it for fun and for the smarter guy Li0liQ :)
TheMachineCharmer
+3  A: 

What you are looking for can be named graph diameter. In order to get it you'll need to calculate the path from any vertex to any other and then go through all of them and find the largest one.
That can be achieved using Dijkstra's algorithm or by simply distance matrix (which can be achieved by powering the adjacency matrix) although it will take more time than Dijkstra's algorithm.

Li0liQ
+1 for getting it first :)
TheMachineCharmer
+1  A: 

Since this is a tree, there is only one path between any pair of vertices. This makes it easier for us to find the diameter of the graph.

The easiest way to do this is by doing two simple traversals of the tree. First, take any arbitrary node to be the root and compute the distances of each vertex from it using a simple DFS/BFS. Now, take the node that is the furthest from the root (this the first node of the most distant pair), and making it the new root, run another traversal of the tree computing distances from there. The most distant node from that is the other node of the pair.

The proof of why this works is left as an exercise.

There is also another way that computes the most distant pair by computing and comparing the most distant pairs for each subtree of the tree starting from an arbitrary node as the root (already mentioned in another answer).

MAK