Post

Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

Explanation for Leetcode 235 - Lowest Common Ancestor of a Binary Search Tree, and its solution in Python.

Problem

Leetcode 235 - Lowest Common Ancestor of a Binary Search Tree

Example:

Desktop View

1
2
3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Desktop View

1
2
3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Approach

Since we’re working with Binary Search Tree(BST), we know our lowest common ancestor would be a value where $p \geq value \leq q$

If both p and q values are greater than current value, then we move right of the current

If both p and q values are smaller than current value, then we move left of the current

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        curr = root

        while curr:
            if p.val < curr.val and q.val < curr.val:
                curr = curr.left
            elif p.val > curr.val and q.val > curr.val:
                curr = curr.right
            else:
                return curr    

Time Complexity and Space Complexity

Time Complexity: $O(h)$ where $h$ is the height of the tree

Space Complexity: $O(1)$

This post is licensed under CC BY 4.0 by the author.