Lowest Common Ancestor of a Binary Search Tree in Python


Suppose we have a binary search tree. we have to find the Lowest common ancestor nodes of two given nodes. The LCA of two nodes p and q is actually as the lowest node in tree that has both p and q as decedent. So if the binary tree is like [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]. The tree will be like −

Here LCA of 2 and 8 is 6

To solve this, we will follow these steps −

  • If the tree is empty, then return null
  • if p and q both are same as root, then return root
  • left := LCA of left subtree of the root using p and q
  • right := LCA of right subtree of the root using p and q
  • if left and right both are non-zero, then return root
  • return left OR right

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def lowestCommonAncestor(self, root, p, q):
      """
      :type root: TreeNode
      :type p: TreeNode
      :type q: TreeNode
      :rtype: TreeNode
      """
      if not root:
         return None
      if p == root or q==root:
         return root
      left = self.lowestCommonAncestor(root.left, p, q)
      right = self.lowestCommonAncestor(root.right, p, q)
      if left and right:
         return root
      return left or right

Input

[6,2,8,0,4,7,9,null,null,3,5]
28

Output

6
raja
Published on 16-Jan-2020 10:26:13
Advertisements