Problem 617
Smallest String Starting From Leaf
Medium · 20 pts · Tree, Depth-First Search, String
Problem
Every node holds a value from 0 to 25, standing for the letters a to z. Each leaf gives a string read from the leaf up to the root. Find the lexicographically smallest of these strings. Remember that a shorter string that is a prefix of a longer one is smaller, so ab comes before aba. Build each path string during a depth-first search, reverse it at every leaf, and keep the smallest.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the lexicographically smallest leaf-to-root string.
Constraints
1 <= number of nodes <= 8500; 0 <= value <= 25
Example input
7 0 1 2 3 4 3 4
Example output
dba
Explanation
In the tree 0 1 2 3 4 3 4 (letters a b c d e d e), the leaf-to-root strings are dba, eba, dca and eca. The smallest is dba.