Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #988: Smallest String Starting From Leaf

In this guide, we solve Leetcode #988 Smallest String Starting From Leaf in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Depth-First Search, String, Backtracking, Binary Tree

Intuition

We must explore combinations of choices, but many branches can be pruned early.

Backtracking enumerates valid candidates while keeping the search space under control.

Approach

Use DFS to build candidates step by step, and backtrack when constraints are violated.

Pruning keeps the exploration practical for typical constraints.

Steps:

  • Define the decision tree.
  • DFS through choices and backtrack.
  • Prune invalid paths early.

Example

Input: root = [0,1,2,3,4,3,4] Output: "dba"

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: ans = chr(ord('z') + 1) def dfs(root, path): nonlocal ans if root: path.append(chr(ord('a') + root.val)) if root.left is None and root.right is None: ans = min(ans, ''.join(reversed(path))) dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root, []) return ans

Complexity

The time complexity is Exponential (worst case). The space complexity is O(depth).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy