Lowest Common Ancestor of Deepest Leaves - Problem

Lowest Common Ancestor of Deepest Leaves

You're given the root of a binary tree, and your task is to find the lowest common ancestor (LCA) of all the deepest leaves in the tree.

What you need to know:
  • A leaf is a node with no children
  • Depth starts at 0 for the root, and increases by 1 for each level down
  • The deepest leaves are all leaf nodes at the maximum depth
  • The LCA is the deepest node that has all target nodes in its subtree

Goal: Find the node that is the common ancestor of all deepest leaves, positioned as low as possible in the tree.

Example: In a tree where the deepest leaves are at depth 3, you need to find their lowest common ancestor - this could be a leaf itself (if there's only one deepest leaf) or an internal node that connects multiple deepest leaves.

Input & Output

example_1.py — Basic Tree
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: Node with value 2
💡 Note: The deepest leaves are nodes 7 and 4 at depth 3. Their lowest common ancestor is node 2 at depth 2.
example_2.py — Single Node
$ Input: root = [1]
Output: Node with value 1
💡 Note: There's only one node which is both the root and the only leaf. It's its own LCA.
example_3.py — Linear Tree
$ Input: root = [0,1,3,null,2]
Output: Node with value 2
💡 Note: The deepest leaf is node 2 at depth 3. Since it's the only deepest leaf, it's its own LCA.

Constraints

  • The number of nodes in the tree will be in the range [1, 1000]
  • 0 ≤ Node.val ≤ 1000
  • Each node value is unique
  • The tree is guaranteed to be a valid binary tree

Visualization

Tap to expand
Lowest Common Ancestor of Deepest Leaves INPUT 3 5 1 6 2 0 8 7 4 Legend: Deepest Leaves (depth 3) LCA (Answer: Node 2) Input: [3,5,1,6,2,0,8, null,null,7,4] ALGORITHM (DFS) 1 DFS Traversal Traverse tree, track depth for each node 2 Find Max Depth Identify deepest level Max depth = 3 3 Return Subtree Info For each node, return (depth, LCA candidate) 4 Compare Depths If left.depth == right.depth --> current node is LCA At Node 2: left(7): depth=3 right(4): depth=3 3 == 3 --> Node 2 is LCA Return (depth=3, node=2) OK FINAL RESULT 3 5 1 6 2 7 4 OUTPUT Node 2 OK - Verified! Node 2 is ancestor of both nodes 7 and 4 Key Insight: The LCA of deepest leaves is found when both left and right subtrees return the same maximum depth. At that point, the current node must be their common ancestor. If depths differ, propagate the deeper subtree's result. Time: O(n), Space: O(h) where h = tree height. Single DFS pass solves both depth finding and LCA computation. TutorialsPoint - Lowest Common Ancestor of Deepest Leaves | DFS Approach
Asked in
Facebook 42 Amazon 35 Google 28 Microsoft 22
78.6K Views
Medium Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen