Given a binary tree with value on each node representing a lowercase letter, find the lexicographically smallest string starting from the leaf to root node
Intuition
We use DFS to find all strings from the root node to the leaf nodes, then reverse the string and compare it withe the largest string.
Approach
We use current
to represent the string starting from the root node to the current node and we use result
to store the currently best result. When we reach the leaf node, we compare the current
with result
and update result
.
Complexity
Time complexity: iterate all nodes once. $$O(n)$$
Space complexity: the string is related to the height of the tree. $$O(\log n)$$
Code
|
|