Leetcode #742: Closest Leaf in a Binary Tree
In this guide, we solve Leetcode #742 Closest Leaf in a Binary Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree. Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: root = [1,3,2], k = 1
Output: 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
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 findClosestLeaf(self, root: Optional[TreeNode], k: int) -> int:
def dfs(root: Optional[TreeNode], fa: Optional[TreeNode]):
if root:
g[root].append(fa)
g[fa].append(root)
dfs(root.left, root)
dfs(root.right, root)
g = defaultdict(list)
dfs(root, None)
q = deque(node for node in g if node and node.val == k)
vis = set(q)
while 1:
node = q.popleft()
if node:
if node.left == node.right:
return node.val
for nxt in g[node]:
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.