In this problem, it is important to fully understand the definition of least common ancestor of 2 nodes:
it means: (from leetcode blog:
点击打开链接)
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous post:Lowest
Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here.
Using the tree above as an example, the LCA of nodes 5 and 1 is 3.
Please note that LCA for nodes 5 and 4 is 5.
Here is the whole code with comments. Really good design by Hawstein.