As reported: LinkedIn coding round 1 (Jan 2025): Closest Leaf in a Binary Tree, returning the leaf's value. A path-based solution (root to target, then each ancestor's other subtree) drew follow-ups: why store the path, do it during the traversal, use BFS, and write it in about ten lines instead of three functions.
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 node with value k. Nearest means the fewest edges travelled along the tree to reach any leaf. A leaf is a node with no children.
This is LeetCode 742 — Closest Leaf in a Binary Tree.
Example 1
root = [1,3,2], k = 1
Output: 2 (3 is equally close; either is accepted)
Example 2
root = [1], k = 1
Output: 1
Example 3
root = [1,2,3,4,null,null,null,5,null,6], k = 2
Output: 3 (leaf 3 is 2 edges away; leaf 6 is 3 away)
Constraints: the tree has 1 to 1000 nodes; 1 ≤ Node.val ≤ 1000; all values are unique; a node with value k exists.
Code runner format: LeetCode's test-case format, one JSON value per line (one line per argument); the tree is a level-order array with null for missing children. Implement findClosestLeaf(root, k). When several leaves are equally close, any of them is accepted: the harness prints "ok" for a leaf at the smallest distance from k.