Lowest Common Ancestor of a Binary Tree IV — LeetCode 1676 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchHash TableBinary Tree
Problem
#1676
Reading time
4 min

The problem

Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.

Example

Input
root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
Output
2
Explanation
The lowest common ancestor of nodes 4 and 7 is node 2.

Python solution

Python
# 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', nodes: 'List[TreeNode]'
    ) -> 'TreeNode':
        def dfs(root):
            if root is None or root.val in s:
                return root
            left, right = dfs(root.left), dfs(root.right)
            if left and right:
                return root
            return left or right

        s = {node.val for node in nodes}
        return dfs(root)

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n + m) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV 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 1676. Lowest Common Ancestor of a Binary Tree IV?
LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is rated Medium on LeetCode.
What is the time complexity of LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV?
The Python solution on this page uses O(n + m) auxiliary space.
What topics does LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV cover?
LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is tagged Tree, Depth-First Search, Hash Table and Binary Tree on LeetCode.
Is LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV a premium problem?
Yes. LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.

Get Stealth Interview