← Tree Traversal

Micro-Drill #212 — Lowest common ancestor (BST)

Tree Traversal Target: 10s

BST property: if both targets < root go left, both > root go right, otherwise root is LCA. O(h) time.

def lowestCommonAncestor(root, p, q):
    while root:
        if p.val &lt; root.val and q.val &lt; root.val:
            root = root.left
        elif p.val &gt; root.val and q.val &gt; root.val:
            root = root.right
        else:
            return root

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #211 Micro #213 →