Loading problem...
You are given the root of a binary tree where each node contains an integer value ranging from 0 to 25, representing the lowercase letters 'a' through 'z' respectively (0 corresponds to 'a', 1 corresponds to 'b', ..., 25 corresponds to 'z').
Your task is to find and return the lexicographically smallest string that can be constructed by starting from any leaf node and traversing upward to the root node.
Understanding Lexicographic Order: A string is lexicographically smaller than another if at the first position where they differ, the character in the first string has a smaller alphabet position, OR if the first string is a prefix of the second string (making it shorter).
For example:
Definition of Leaf Node: A leaf node is a node that has no left or right children.
Path Construction: The path string is built by starting at a leaf node, converting each node's value to its corresponding character, and appending characters as you move up toward the root. This means the leaf's character appears first in the string and the root's character appears last.
root = [0,1,2,3,4,3,4]"dba"The tree structure is:
a(0)
/
b(1) c(2)
/ \ /
d(3) e(4) d(3) e(4)
All possible leaf-to-root paths and their strings:
Comparing all strings: "dba" < "dca" < "eba" < "eca" The lexicographically smallest is "dba".
root = [25,1,3,1,3,0,2]"adz"The tree structure is:
z(25)
/
b(1) d(3)
/ \ /
b(1) d(3) a(0) c(2)
All possible leaf-to-root paths and their strings:
Comparing all strings: "adz" < "bbz" < "cdz" < "dbz" The lexicographically smallest is "adz".
root = [2,2,1,null,1,0,null,0]"abc"The tree structure is:
c(2)
/
c(2) b(1)
\ /
b(1) a(0)
/
a(0)
All possible leaf-to-root paths and their strings:
Comparing all strings: "abc" < "abcc" The lexicographically smallest is "abc".
Constraints