1218. Lowest Common Ancestor of Deepest Leaves
My accepted Python solution to LeetCode problem 1218, Lowest Common Ancestor of Deepest Leaves, running in 1ms.
- Difficulty: Medium
- Python
- Runtime 1ms
- Memory 17.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 1ms, memory 17.6MB, accepted 2026-01-02.
# 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(node):
# Returns (depth, lca_node)
if not node:
return (0, None)
left_depth, left_lca = dfs(node.left)
right_depth, right_lca = dfs(node.right)
if left_depth > right_depth:
return (left_depth + 1, left_lca)
elif right_depth > left_depth:
return (right_depth + 1, right_lca)
else:
# Equal depths - current node is the LCA
return (left_depth + 1, node)
return dfs(root)[1]