Problem 1123

Abstract / Summary

Find the deepest leaves in a tree and return the lowest common ancestor of those leaves.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1123.py

class Solution:
    def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def deeper(node):
            if not node:
                return None, 0

            l, ld = deeper(node.left)
            r, rd = deeper(node.right)

            # return deepest child node
            if ld > rd:
                return l, ld + 1
            if rd > ld:
                return r, rd + 1

            # both are the same, potential ancestor found
            return node, ld + 1 # ld == rd

        shared, depth = deeper(root)
        return shared
20 lines | 593 bytes | submitted October 31, 2023 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Hash Table
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method lcaDeepestLeaves that computes the lowest common ancestor (LCA) of the deepest leaf nodes in a binary tree. The algorithm relies on a single depth-first recursion that simultaneously discovers the deepest depth and the node that serves as the common ancestor for all deepest leaves. By returning both a candidate node and its associated depth from each recursive call, the solution avoids multiple traversals and keeps the logic compact.

Recursive Helper

The core of the algorithm is the nested function deeper. This helper receives a tree node and returns a tuple consisting of a reference to the deepest relevant node (or ancestor) and an integer representing the depth of the subtree rooted at the given node. The function is defined as follows:

def deeper(node):
    if not node:
        return None, 0
    l, ld = deeper(node.left)
    r, rd = deeper(node.right)
    if ld > rd:
        return l, ld + 1
    if rd > ld:
        return r, rd + 1
    return node, ld + 1  # ld == rd

The recursion proceeds to the left and right children, collects their results, and then decides which result to propagate upward based on depth comparison.

Base Case Handling

When the recursion reaches a null reference, the function returns a pair of None and 0. This base case establishes that an empty subtree contributes no depth and no candidate node. The explicit check if not node: ensures that leaf nodes are correctly processed: the recursive calls on their children both yield (None, 0), leading to the leaf itself being identified as the deepest node with depth 1.

Depth Comparison Logic

After obtaining the left result (l, ld) and the right result (r, rd), the function compares the depths ld and rd. If the left depth exceeds the right depth, the left candidate l is returned together with an incremented depth ld + 1. Conversely, if the right depth is greater, the right candidate r and rd + 1 are returned. When the depths are equal, the current node is recognized as a potential common ancestor for the deepest leaves, and the function returns the current node with depth ld + 1. This conditional structure ensures that the deepest branch is always favored, while equal depths trigger an ancestor selection.

Return of Shared Ancestor

The outer method invokes deeper on the root of the tree and extracts the first element of the returned tuple, which represents the shared ancestor of the deepest leaves. The final lines are:

shared, depth = deeper(root)
return shared

The variable depth is captured but not used further, illustrating that the primary interest lies in the node reference.

Edge Cases

The implementation gracefully handles several edge conditions without additional code. An empty tree (root is None) triggers the base case immediately, resulting in shared being None, which is a correct representation of the absence of any nodes. A tree consisting of a single node leads to both recursive calls on its children returning (None, 0), causing the equality branch to select the sole node as the LCA of the deepest leaf (which is itself). Trees where the deepest leaves are located exclusively on one side are correctly resolved because the depth comparison will always favor the deeper side, propagating the deepest leaf upward as the candidate. When deepest leaves appear on both sides at the same depth, the equality condition selects the current node, thereby delivering the lowest common ancestor that spans both subtrees.

Performance Optimizations

The algorithm achieves optimal efficiency by performing a single post-order traversal of the tree. Each node is visited exactly once, and the depth information is computed on the fly, eliminating the need for separate passes to locate deepest leaves and then to compute their LCA. By returning both the candidate node and its depth together, the function avoids auxiliary data structures such as stacks or queues, reducing memory overhead. The incremental depth calculation (ld + 1 or rd + 1) leverages the already computed child depths, ensuring that no redundant arithmetic is performed. This tight coupling of depth propagation and ancestor selection constitutes the primary performance advantage of the implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree that grows downwards like branches. Each branch has some nodes on it. Some branches are longer than others, stretching deeper into the ground.

The goal is to find the common ancestor that sits right above all the deepest nodes. Think of this like looking for the split point where all the bottom-most leaves finally meet up.

The deeper function acts like an explorer. It starts at the top and travels down every single path to the very end. As it climbs back up, it carries a backpack that tells it how long that specific path was.

When the explorer reaches a spot where two branches meet, it looks at the numbers in the backpacks from the left side and the right side. If the left side has a longer path, it keeps going that way. If the right side is longer, it picks that path instead.

If the explorer finds that both the left and right sides have paths of the exact same length, it realizes that the current spot is the special meeting point for all those deepest leaves. It marks this spot and carries that information all the way back to the top. By the time it finishes checking every branch, the spot it kept track of is the one that connects all the deepest parts of the tree together.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.23 | σ = 0.93

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java C# Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
30 links | 19 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

8 solutions   October 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality