Closest Leaf in a Binary Tree Problem
Description
LeetCode Problem 742.
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. Also, a node is called a leaf if it has no children.
Example 1:

Input: root = [1,3,2], k = 1
Output: 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
Example 2:

Input: root = [1], k = 1
Output: 1
Explanation: The nearest leaf node is the root node itself.
Example 3:

Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2
Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]. 1 <= Node.val <= 1000- All the values of the tree are unique.
- There exist some node in the tree where
Node.val == k.
Solution
Approach: Parent Pointers + BFS
The closest leaf is not always below the node with value k. In example 3, the node 2 has the leaf 6 three edges below it, but going up to 1 and down to 3 takes only two edges. So we need to be able to move up as well as down, which means treating the tree as an undirected graph.
- Traverse the tree once (an explicit stack works fine) and record each node's parent in a hash map. During the same walk, remember the node whose value is
k. - Run a breadth-first search from that node. The neighbors of a node are its left child, its right child and its parent. Keep a
seenset so we never walk back over an edge. - BFS visits nodes in order of distance from
k, so the first leaf it takes off the queue (a node with no children) is a closest leaf.
Two details: the node k can be a leaf itself, in which case the answer is k (example 2). And a root with only one child is not a leaf, even though it has only one neighbor in the graph, so test for "no children" rather than "one neighbor". When several leaves are equally close, any of them is accepted.
Complexity: O(n) time and O(n) extra space for the parent map, the queue and the seen set.
# 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:
# Walk the tree once to remember every node's parent and find the node with value k.
parent = {root: None}
start = None
stack = [root]
while stack:
node = stack.pop()
if node.val == k:
start = node
for child in (node.left, node.right):
if child:
parent[child] = node
stack.append(child)
# BFS from k over the tree as an undirected graph: the first leaf reached is the closest one.
queue = [start]
seen = {start}
for node in queue:
if node.left is None and node.right is None:
return node.val
for nxt in (node.left, node.right, parent[node]):
if nxt and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return -1 # never reached: every tree has a leaf