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)
As everybody here seems to know, if you keep a note of the distance each node is from the root, then once you have found the lowest common ancestor of the two nodes you can work out the distance they are from each other in constant time.
If you do one time work only linear in the size of the tree it turns out that you can then find the lowest common ancestor of any two nodes in constant time (no matter how deep the tree is). See http://en.wikipedia.org/wiki/Lowest_common_ancestor
The Baruch Schieber and Uzi Vishkin algorithm for lowest common ancestor is entirely practical to use and to program.