Possible Duplicate:
How can I find the common ancestor of two nodes in a binary tree?
first common ancestor of a binary tree
I have a binary tree as below. I need to find the least common ancestor (LCA). e.g LCA of 6 and 4 is 1, LCA of 4 and 5 is 2.
1
/ \
2 3
/ \ / \
4 5 6 7
Can anyone please suggest how should I approach and solve this problem?
Start with an ordinary depth-first search algorithm:
Now, adapt this to take two “target” parameters, target1 and target2.
When the search for target1 takes you left, and the search for target2 takes you right, you’ve found the LCA.
This assumes that both targets actually do exist. If you need to assert that they do, you’ll need to continue the search after finding the potential LCA.