Smallest String Starting From Leaf

Medium Topics Company Tags

Interpret each node value as a lowercase letter: 0 is a, 1 is b, and so on through 25 for z. For each leaf, form a string by following the path from that leaf upward to the root. Return the lexicographically smallest of these strings. A leaf has no children.

Compare strings at their first differing letter. If one string is a prefix of the other, the shorter string comes first; for example, ab comes before aba. Remember that the strings run from leaf to root, rather than root to leaf.

Examples use level-order arrays. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Smallest String Starting From Leaf, example 1: illustration of the example

Input: root = [2,1,0]

Output: "ac"

Explanation: The left leaf produces bc and the right leaf produces ac. Since a comes before b, ac is the smaller string.

Example 2:

Smallest String Starting From Leaf, example 2: illustration of the example

Input: root = [0,0,0,0]

Output: "aa"

Explanation: The left branch produces aaa, and the right leaf produces aa. The shorter string aa is a prefix of aaa, so aa comes first.

Example 3:

Smallest String Starting From Leaf, example 3: illustration of the example

Input: root = [25]

Output: "z"

Explanation: The root is also a leaf. Its value 25 represents z, which is the only candidate string.

Constraints:

  • The tree contains between 1 and 8500 nodes.
  • 0 <= Node.val <= 25


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.