Wednesday, July 2, 2008

Find the least common ancestor of two nodes in a binary tree

From the root, traverse until the current node value is between the value of the two nodes.

50
/ \
40 60
/ \ / \
30 45 55 65
/ \
20 35

For example, find the least common ancestor (LCA) of 20 and 45 in the above tree. The root node, 50, is not between 20 and 45. We traverse left because both target nodes are less than 50. Now since 40 is between 20 and 45, this is the LCA.

No comments: