Smallest String Starting From Leaf

You are given the root of a binary tree where every node holds a value from 0 to 25, standing for the letters 'a' to 'z'. Every path from a leaf up to the root spells a string, read starting at the leaf. Return the lexicographically smallest such string. A shorter string that is a prefix of a longer one is the smaller of the two.

30:00

Smallest String Starting From Leaf
medium
Free written solution
Topics
Companies

You are given the root of a binary tree where every node holds a value from 0 to 25, standing for the letters 'a' to 'z'. Every path from a leaf up to the root spells a string, read starting at the leaf. Return the lexicographically smallest such string. A shorter string that is a prefix of a longer one is the smaller of the two.

Example 1:
Input: {"root":[0,1,2,3,4,3,4]}
Output: dba
Constraints:
  • The number of nodes in the tree is in the range [1,8500][1, 8500].

  • 0≤Node.val≤250 \leq \text{Node.val} \leq 25

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[0,1,2,3,4,3,4]}

Each node is a letter. Walk every root-to-leaf path with DFS, read it backwards from the leaf, and keep the smallest string. best starts as '~', which is bigger than any letter string.

abcdede

DFS path, root to current (read it right to left)

empty

best so far

best

none yet

Variables
VariableValue
path
best~
DepthFunction Call
Stack empty
0/19