I have been looking at the pasted code below in the Discuss tab of Leetcode and I feel I don't fully understand recursion. The question is about finding the common ancestor of 2 nodes in a binary search tree.
def lowestCommonAncestor(self, root, p, q):
if p.val < root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
Could explain to me how root
is changed such that it gives the answer without its value being updated? I see root
being passed into the main function (an argument like p
and q
) but the recursive calls only take root.left
and root.right
.
Could you clarify the recursion with an explanation of finding the common ancestor of 3 and 5?
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
The Stackoverflow accepted answer here uses recursion but doesn't answer my question.
Where I found the code: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/64963/3-lines-with-O(1)-space-1-Liners-Alternatives