lowest-common-ancestor-of-a-binary-search-tree.py
trees/lowest-common-ancestor-of-a-binary-search-tree.py · Python · 759 B · 2026-02-15 06:40
# Recursive or iterative. # trees # Recursive - O(log n) time, O(log n) space def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root.val < p.val and root.val < q.val: return lowestCommonAncestor(root.right, p, q) elif root.val > p.val and root.val > q.val: return lowestCommonAncestor(root.left, p, q) else: return root # Iterative - O(log n) time, O(1) space def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': while root: if root.val < p.val and root.val < q.val: root = root.right elif root.val > p.val and root.val > q.val: root = root.left else: return root return None