Lowest Common Ancestor of Deepest Leaves — LeetCode 1123 Python Solution
- Problem
- #1123
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
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
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.