Smallest String Starting From Leaf (LeetCode 988): Solution and Explanation

Medium
String
Backtracking
Tree
Depth First Search
Binary Tree

Each node of a binary tree holds a letter from 'a' to 'z'. Every leaf-to-root path spells a string read from the leaf upward. Return the lexicographically smallest of those strings.

Intuition

The string starts at the leaf, so its first letter is the deepest one. A small letter near the root decides almost nothing, because it lands at the end of the string. That rules out a greedy walk from the root that always picks the smaller child.

What does work is checking every leaf. A DFS already keeps the root-to-node path on its stack, and reading that stack backwards at a leaf gives exactly the leaf-to-root string. Compare it with the best so far and move on.

Approach: DFS with a path stack

  1. Set best = '~', a sentinel that sorts after every lowercase string.
  2. DFS from the root. On entering a node, push its letter onto path.
  3. At a leaf, reverse path into cand. If cand < best, set best = cand.
  4. Recurse into the left and right children, then pop the letter before returning.
  5. Return best after the DFS finishes.

Step-by-step example

root = [0,1,2,3,4,3,4]
  1. The root is 'a', its children are 'b' and 'c', and the leaves are 'd', 'e' under 'b' and 'd', 'e' under 'c'.
  2. Path a, b, d reaches a leaf. Read backwards it is "dba", the first candidate, so best = "dba".
  3. Path a, b, e gives "eba". It differs at index 0 and 'e' > 'd', so best stays "dba".
  4. Path a, c, d gives "dca". It differs at index 1 and 'c' > 'b', so best stays.
  5. Path a, c, e gives "eca", which is larger again. Return "dba".

Code: Python, Java, C++

1class Solution:
2    def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
3        best = '~'
4        path = []
5
6        def dfs(node):
7            nonlocal best
8            if not node:
9                return
10            path.append(chr(ord('a') + node.val))
11            if not node.left and not node.right:
12                cand = ''.join(reversed(path))
13                if cand < best:
14                    best = cand
15            dfs(node.left)
16            dfs(node.right)
17            path.pop()
18
19        dfs(root)
20        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * h)

Every node is visited once, and each leaf builds and compares a string of length up to the tree height h.

Space

O(h)

The path stack and the recursion both hold at most h entries, plus the best string of length up to h.

Other approaches

Pass the string down the recursion (time O(n * h), space O(h^2))

Call dfs(child, letter + suffix) so each call already has the leaf-to-root string built from the top. It is shorter to write but creates a new string at every node, which costs O(n * h) memory traffic.

BFS with parent pointers (time O(n * h), space O(n))

Record each node's parent during a level-order walk, then for every leaf climb the parent chain to build its string. Same comparisons, more bookkeeping.

Common mistakes

  • Greedy descent: always going to the child with the smaller letter fails, because the letters near the root end up at the end of the string.
  • Reading the path in root-to-leaf order. The string must start at the leaf.
  • Treating a node with one child as a leaf. Only nodes with no children end a string.
  • Starting best as an empty string. The empty string is smaller than everything, so nothing would ever replace it.

Frequently asked questions

Why can't I just compare letters level by level from the top?

Because the root letter is the last character of every string. The comparison is decided by the deepest letters first, and those come from different leaves at different depths.

How does the prefix rule show up here?

If one leaf string is a prefix of another, the shorter one wins. With root [1,0,1,null,null,0] the strings are "ab" and "abb", so the answer is "ab".

Why is '~' a safe starting value?

'~' has a larger character code than any lowercase letter, so every real leaf string compares smaller and replaces it on the first leaf.

Is recursion depth a concern?

A tree of 8500 nodes can be a single chain. In Python that exceeds the default recursion limit, so either raise it or switch to an explicit stack.