Lowest Common Ancestor of Deepest Leaves — LeetCode 1123 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#1123
Reading time
4 min

The problem

Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. Recall that: The node of a binary tree is a leaf if and only if it has no children The depth of the root of the tree is 0.

Example

Input
root = [3,5,1,6,2,0,8,null,null,7,4]
Output
[2,7,4]
Explanation
We return the node with value 2, colored in yellow in the diagram.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(root):
            if root is None:
                return None, 0
            l, d1 = dfs(root.left)
            r, d2 = dfs(root.right)
            if d1 > d2:
                return l, d1 + 1
            if d1 < d2:
                return r, d2 + 1
            return root, d1 + 1

        return dfs(root)[0]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1123. Lowest Common Ancestor of Deepest Leaves 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 1123. Lowest Common Ancestor of Deepest Leaves?
LeetCode 1123. Lowest Common Ancestor of Deepest Leaves is rated Medium on LeetCode.
What is the time complexity of LeetCode 1123. Lowest Common Ancestor of Deepest Leaves?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1123. Lowest Common Ancestor of Deepest Leaves?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1123. Lowest Common Ancestor of Deepest Leaves cover?
LeetCode 1123. Lowest Common Ancestor of Deepest Leaves is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table 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.

Get Stealth Interview