Lowest Common Ancestor of Deepest Leaves in Python

Suppose we have a rooted binary tree, we have to return the lowest common ancestor of its deepest leaves. We have to keep in mind that −

  • The node of a binary tree is a leaf node if and only if it has no children

  • The depth of the root of the tree is 0, and when the depth of a node is d, the depth of each of its children is d+1.

  • The lowest common ancestor of a set S of nodes in the node A with the largest depth such that every node in S is in the subtree with root A.

If the input is [1,2,3,4,5],

then the output will be [2,4,5]

To solve this, we will follow these steps −

  • Define a method called solve(), this will take node, this will work as follows −

  • if node is not present, then return a list with [0, None]

  • if left and right subtrees are empty of node, then return a list with [1, None]

  • d1, l := solve(left of node), d2, r := solve(right of node)

  • if d1 > d2 , then return a list with values [d1 + 1, l]

  • otherwise when d2 > d1, then return a list with values [d2 + 1, r]

  • return a list with values [d1 + 1, node]

  • In the main method, we will perform −

  • list := solve(root)

  • return list[1]


Let us see the following implementation to get a better understanding −

 Live Demo

class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   while (len(que)):
      temp = que[0]
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
            temp.left = TreeNode(0)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
            temp.right = TreeNode(0)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
def print_tree(root):
   #print using inorder traversal
   if root is not None:
      print(root.data, end = ', ')
class Solution(object):
   def lcaDeepestLeaves(self, root):
      return self.solve(root)[1]
   def solve(self,node):
      if not node:
         return [0,None]
      if not node.left and not node.right:
         return [1,node]
      d1,l = self.solve(node.left)
      d2,r = self.solve(node.right)
      if d1>d2:
         return [d1+1,l]
      elif d2>d1:
         return [d2+1,r]
      return [d1+1,node]
ob = Solution()
root = make_tree([1,2,3,4,5])




4, 2, 5,