Skip to main content
Back to problems
#988
Medium Algorithms

Smallest string starting from leaf

String Backtracking Tree Depth-First Search Binary Tree
61.1% acceptance
Feb 27, 2026
2409
336
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. As a reminder, any shorter prefix of a string is lexicographically smaller. For example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn smallest_from_leaf(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>) -> String {
    let mut best = String::new();
    fn dfs(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, path: &mut Vec<u8>, best: &mut String) {
      if let Some(n) = node {
        let n = n.borrow();
        path.push(b'a' + n.val as u8);
        if n.left.is_none() && n.right.is_none() {
          let s: String = path.iter().rev().map(|&c| c as char).collect();
          if best.is_empty() || s < *best { *best = s; }
        }
        dfs(&n.left, path, best);
        dfs(&n.right, path, best);
        path.pop();
      }
    }
    dfs(&root, &mut Vec::new(), &mut best);
    best
  }
}