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 โ†’ root direction
  • 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
Smallest String From Leaf - Visual GuideabcdedePath 1dโ†’bโ†’a"dba"Path 2eโ†’bโ†’a"eba"Path 3dโ†’cโ†’a"dca"Path 4eโ†’cโ†’a"eca"Result: "dba"Lexicographically smallest string
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.
Asked in
Google 42 Amazon 38 Microsoft 25 Meta 18
42.8K Views
Medium Frequency
~18 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen