lowest common ancestor (LCA) of two given nodes; getting null for one set of values; getting correct answer for another set

177 views Asked by At

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)
1

There are 1 answers

0
Cardstdani On

You may want to try the following implementation:

def lca(root, p, q):
    if root is None:
        return None
    if(root.val > p.val and root.val > q.val):
        return lca(root.left, p, q)
 
    if(root.val < p.val and root.val < q.val):
        return lca(root.right, p, q)
 
    return root