Closest Leaf in a Binary Tree - Problem
Imagine you're exploring a binary tree and need to find the shortest path from a specific target node to any leaf node. Given the root of a binary tree where every node has a unique value and a target integer k, your task is to return the value of the nearest leaf node to the target k.
The distance is measured by the minimum number of edges you need to traverse to reach any leaf from the target node. Remember, a leaf node is one that has no children (both left and right are null).
Key Points:
- You can move both up and down the tree from the target node
- Distance is measured in number of edges, not node values
- A leaf has no left or right children
- All node values are unique
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [1,3,2], k = 1
โบ
Output:
2
๐ก Note:
The tree has structure: 1(root) with children 3(left) and 2(right). Both 3 and 2 are leaves. From node 1 (our target k), we can reach leaf 3 in 1 step and leaf 2 in 1 step. Since both have the same distance, we return either one. The answer returns 2.
example_2.py โ Target is Leaf
$
Input:
root = [1,2,3,4,null,null,null,5,null,6], k = 2
โบ
Output:
3
๐ก Note:
Tree structure: 1โ(2,3), 2โ(4,null), 4โ(5,null), 5โ(6,null). Target k=2 is not a leaf (has child 4). Leaves are: 3, 6. Distance from 2 to 3: go up to 1, then down to 3 = 2 steps. Distance from 2 to 6: down through 4โ5โ6 = 3 steps. Closest leaf is 3.
example_3.py โ Target is Leaf Node
$
Input:
root = [1,2,3], k = 3
โบ
Output:
3
๐ก Note:
The tree is 1โ(2,3). Target k=3 is already a leaf node (no children). When the target itself is a leaf, the distance is 0, so we return the target value 3.
Visualization
Tap to expand
Understanding the Visualization
1
Map the Building
Convert the tree structure into a bidirectional map where each room (node) knows all its connected rooms (parent and children)
2
Start Your Search
Begin a systematic search from your current room (target k), exploring all connected rooms level by level
3
Check Each Room
For each room you enter, check if it's an exit door (leaf node with no children)
4
Found the Nearest Exit
The first exit door you find is guaranteed to be the closest one due to the level-by-level search
Key Takeaway
๐ฏ Key Insight: By converting the tree to an undirected graph, we can explore in all directions. BFS guarantees the first exit (leaf) we find is the closest to our starting position.
Time & Space Complexity
Time Complexity
O(n)
O(n) to build graph + O(n) for BFS traversal in worst case
โ Linear Growth
Space Complexity
O(n)
O(n) for adjacency list + O(n) for BFS queue and visited set
โก Linearithmic Space
Constraints
- The number of nodes in the tree is in the range [1, 103]
- 1 โค Node.val โค 103
- All Node.val are unique
- k is guaranteed to exist in the tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code