Problem Description
Given a binary tree where each node's value is in the range [0, 25] (each representing a lowercase letter from 'a' to 'z'), return the lexicographically smallest string that starts at a leaf and ends at the root. Each string is built by concatenating the characters corresponding to the node values from leaf to root.
Key Insights
- Use a depth-first search (DFS) to traverse the tree.
- Build the path by prepending the character of the current node; this naturally forms the string from leaf to root.
- At every leaf node, compare the constructed string with the smallest string found so far.
- Use a placeholder value like "~" (which is lexicographically larger than any lowercase letter) to initialize the smallest string.
- Edge Case: Trees with only a single node.
Space and Time Complexity
Time Complexity: O(N^2) in the worst case, due to the cost of string concatenation when the tree is skewed. Space Complexity: O(N) due to the recursion stack and the space required to maintain the current path.
Solution
We employ a depth-first search to traverse the binary tree starting from the root. As we traverse, we build the path string by prepending the current node’s character so that at the leaf, the string is in the correct order (leaf to root). When a leaf is encountered, we compare the formed string with the smallest string found so far, updating our record if needed. The DFS ensures every leaf is visited with the correct accumulated path. Key data structures include recursion for DFS and a string to maintain the path.