Smallest String Starting From Leaf Problem
Description
LeetCode Problem 988.
You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.
Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
As a reminder, any shorter prefix of a string is lexicographically smaller.
- For example, "ab" is lexicographically smaller than "aba".
A leaf of a node is a node that has no children.
Example 1:
Input: root = [0,1,2,3,4,3,4]
Output: "dba"
Example 2:
Input: root = [25,1,3,1,3,0,2]
Output: "adz"
Example 3:
Input: root = [2,2,1,null,1,0,null,0]
Output: "abc"
Constraints:
- The number of nodes in the tree is in the range [1, 8500].
- 0 <= Node.val <= 25
Solution
Approach: DFS with the Current Path
Every candidate string is a root-to-leaf path read backwards. So walk the tree with DFS, keeping the letters on the path from the root to the current node, and compare a full candidate at every leaf.
- On entering a node, append its letter (
'a' + val) topath. - If the node is a leaf, reverse
pathto get the string from this leaf up to the root, and keep it if it is smaller than the best so far. - Recurse into both children, then remove the letter again (backtrack) before returning.
The tempting shortcut is to decide locally, for example to always go down into the child with the smaller letter, or to build the answer bottom-up as min(best string of each child) + node's letter. Both are wrong, because adding the same suffix can change which string is smaller. In the tree [25,1,0,0] the two leaf strings are "abz" and "az": going into the smaller child a (value 0) gives "az", but "abz" is smaller. Comparing complete strings at the leaves avoids this.
Complexity: O(n · h) time, where n is the number of nodes and h the height of the tree, since each leaf builds and compares a string of length at most h. O(h) space for the path and the recursion.
class Solution:
def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
best = None
path = [] # letters from the root down to the current node
def dfs(node: Optional[TreeNode]) -> None:
nonlocal best
if node is None:
return
path.append(chr(ord("a") + node.val))
if node.left is None and node.right is None:
candidate = "".join(reversed(path)) # read from the leaf up to the root
if best is None or candidate < best:
best = candidate
dfs(node.left)
dfs(node.right)
path.pop()
dfs(root)
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.