I was writing a program for finding the Lowest Common Ancestor of a pair of nodes in a Binary Search Tree(given the elements exist in the tree). My Logic was:
- Start from root.
- If both elems greater than the current element then return root(this is where it differs).
- Else if both lesser than root, then recurse on left subtree.
- else return root(one is lesser other is greater).
However, Algos found online(http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-search-tree.html) change step 2, in this case they recurse on right subtree and therefore for the following tree:
2
/ \
1 4
/ \
3 5
and input 3 and 5, my algo gives 2, while the other algos give 4 as the output.
So, is it me understanding the definition of LCA wrong ('cause 2 is lower than 4 and is a common ancestor) or is my Algo correct.