Faaez Razeen

Lowest Common Ancestor

  • 2 min read
  • LC-Medium
  • Binary-search-tree

3 years ago

Solution

TimeSpaceExplanation
O(log n) or O(h)O(1)
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': cur = root while cur: if p.val < cur.val and q.val < cur.val: cur = cur.left elif p.val > cur.val and q.val > cur.val: cur = cur.right else: return cur