Lowest common ancestor in binary tree

Greetings all !!

Have been trying to figure out a solution to this pretty common problem. There is another instance of this question in codechef forums itself (Finding lowest common ancestor in Binary Tree - general - CodeChef Discuss). Unlike the solution presented there , the question is usually given with two integer values as input rather than two node pointers.There are tons of solutions all over the internet but I have not been able to find a correct solution till now that handles all the following cases.

  1. One of the values might not be present in the tree.

  2. Duplicate nodes for the same value.

  3. the LCA might contain be of the input values themselves.

Any suggestions ?

Edit: One possible solution could be using the concept shown here Programming Interview: Lowest Common Ancestor Binary Tree - YouTube. However the complexity would be O(N^2). Any possible solutions that use recursion ?

go to link Static Trees this will help you more than you need now.