This question was asked to me in an interview: I have a binary tree and I have to find the common ancestor (parent) given two random nodes of that tree. I am also given a point
I think you could just do a search simultaneously for both nodes; the point at which the search diverges is the common ancestor.
commonAncestor tree a b:
value :=
if (a < value) && (b < value)
then commonAncestor (left tree) a b
else if (a > value) && (b > value)
then commonAncestor (right tree) a b
else tree
Interestingly this approach would scale to more than two nodes (check for all of them to be on the left side of tree
, etc.)