Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
- root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8; expected Output = 6; My output = 6
- root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4; expected Output = 2; My output = null
On using print I am getting the required value but when I return its null.
I think I am missing something very basic here.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def bst(root,p=p.val,q=q.val):
if not root:
return
if p<root.val and q<root.val:
bst(root.left)
elif p>root.val and q>root.val:
bst(root.right)
else:
return root
return bst(root)
You may want to try the following implementation: