smj007

Untitled

Jun 20th, 2022
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. class Solution:
  2.     def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
  3.        
  4.         if not root:
  5.             return None
  6.        
  7.         # if either of them equals the root, root is the LCA
  8.         if root == p or root == q:
  9.             return root
  10.        
  11.         # if both lie to the left, explore left subtree
  12.         if p.val < root.val and q.val < root.val:
  13.             return self.lowestCommonAncestor(root.left, p, q)
  14.        
  15.         # if both lie to the right, explore right subtree
  16.         if p.val > root.val and q.val > root.val:
  17.             return self.lowestCommonAncestor(root.right, p, q)
  18.        
  19.         # if both lie on the either side of the root, then root is the lowest common ancestor
  20.         return root
Advertisement
Add Comment
Please, Sign In to add comment