MediumNo. 0236

Lowest Common Ancestor of a Binary Tree — LeetCode 236 Python Solution

Topics
Tree, Depth-First Search, Binary Tree
Reading time
3 min

The problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

This statement is abridged. Read the full problem on LeetCode.

Example

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

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def lowestCommonAncestor(
        self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
    ) -> "TreeNode":
        if root in (None, p, q):
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        return root if left and right else (left or right)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 236. Lowest Common Ancestor of a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 236. Lowest Common Ancestor of a Binary Tree?

LeetCode 236. Lowest Common Ancestor of a Binary Tree is rated Medium on LeetCode.

What is the time complexity of LeetCode 236. Lowest Common Ancestor of a Binary Tree?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 236. Lowest Common Ancestor of a Binary Tree?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 236. Lowest Common Ancestor of a Binary Tree cover?

LeetCode 236. Lowest Common Ancestor of a Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.