Faaez Razeen

Lowest Common Ancestor of a Binary Tree

  • 2 min read
  • LC-Medium
  • Binary Tree

3 years ago

Solution

TimeSpaceExplanation
O(n)O(n)
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root if right: # Alternatively, condition could be written as if left is None return right if left: # Alternatively, condition could be written as if right is None return left

Alternative Code (A bit more hard to understand)

def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None or root == p or root == q: 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