Smallest String Starting From Leaf - Problem
Imagine you're working with a special binary tree where each node contains a letter from 'a' to 'z' (represented by values 0-25). Your task is to find the lexicographically smallest string that starts from any leaf node and travels up to the root.
Think of it like finding the "earliest" path in a dictionary - just like how "ab" comes before "aba" alphabetically. You need to explore all possible paths from leaves to root and return the one that would appear first in a dictionary.
Key Points:
- A leaf node has no children
- The string is built from
leaf โ rootdirection - Each node value (0-25) maps to letters 'a'-'z'
- Return the lexicographically smallest such string
Example: If a path gives you nodes [7, 4, 11, 11, 14] from leaf to root, this translates to string "hello".
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [0,1,2,3,4,3,4]
Tree structure:
a(0)
/ \
b(1) c(2)
/ | | \
d(3) e(4) d(3) e(4)
โบ
Output:
"dba"
๐ก Note:
There are four possible paths from leaves to root: "dba", "eba", "dca", "eca". The lexicographically smallest is "dba".
example_2.py โ Single Path
$
Input:
root = [25,1,3,1,3,0,2]
Tree structure:
z(25)
/ \
b(1) d(3)
/ | | \
b(1) d(3) a(0) c(2)
โบ
Output:
"adz"
๐ก Note:
The paths are "bbz", "ddz", "adz", "cdz". The smallest lexicographically is "adz".
example_3.py โ Edge Case - Single Node
$
Input:
root = [0]
Tree structure: a(0)
โบ
Output:
"a"
๐ก Note:
Single node tree, so the only path from leaf to root is just "a".
Constraints
- The number of nodes in the tree is in the range [1, 8500]
- 0 โค Node.val โค 25
- Each node value represents a letter from 'a' to 'z' (0 = 'a', 1 = 'b', ..., 25 = 'z')
- Important: The string is built from leaf to root, not root to leaf
Visualization
Tap to expand
Understanding the Visualization
1
Start DFS
Begin traversal from root with empty string
2
Build Upward
At each node, prepend its letter to current path string
3
Check Leaves
When reaching a leaf, compare current string with minimum found
4
Track Minimum
Keep the lexicographically smallest string throughout traversal
5
Return Result
After visiting all paths, return the globally smallest string
Key Takeaway
๐ฏ Key Insight: Build strings during DFS traversal and compare immediately at leaves, avoiding the need to store all paths. This optimizes both time and space complexity while maintaining correctness.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code