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
🏠 Family Tree Reunion Planning👴 Grandpa👨 Dad👩 Mom👦 Kid1👧 Kid2👶 Baby1👶 Baby2👼 Gen3👼 Gen3Left Branch: Youngest at Generation 3 (depth 3)Right Branch: Youngest at Generation 2 (depth 2)Meeting Point: Dad's house (connects to deepest generation)REUNION HERE!
Understanding the Visualization
1
Explore Family Branches
Visit each family branch (subtree) to find the youngest generation depth and their meeting point
2
Compare Branch Depths
Compare the youngest generation depth between left and right family branches
3
Choose Meeting Point
If branches have different depths, choose the meeting point from the deeper branch. If same depth, current ancestor becomes the meeting point
Key Takeaway
🎯 Key Insight: The optimal solution visits each family member once and simultaneously tracks both the deepest generation and the best meeting point, making it efficient with O(n) time complexity.
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