Lowest Common Ancestor of Deepest Leaves in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 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 is 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]

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def lcaDeepestLeaves(self, root):
      """
      :type root: TreeNode
      :rtype: TreeNode
      """
      return self.solve(root)[1]
      return temp
   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]

Input

[1,2,3,4,5]

Output

[2,4,5]
raja
Published on 17-Mar-2020 06:54:49
Advertisements