↓Skip to main content
  1. LeetCode/

LeetCode 988: Smallest String Starting From Leaf

·1 min· ·
LeetCode Medium String Backtracking Tree Depth-First-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-04-17

  • Submissions: Accepted (first try)

Approach
#

The string reads from leaf to root, so prepend each character on the way down (Tree Template 1); at a leaf the string is complete, compared with the best so far. Picking the smaller side at each node and building upward is wrong, since a shared suffix can change the comparison.

My Solution
#

class Solution:
    def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
        best = None
        def dfs(node, s):
            nonlocal best
            if not node:
                return
            s = chr(ord("a") + node.val) + s
            if not node.left and not node.right:
                if best is None or s < best:
                    best = s
            dfs(node.left, s)
            dfs(node.right, s)
        dfs(root, "")
        return best

Complexity
#

Time O(n · h), space O(h).

Mistakes to Avoid
#

  • The direction is leaf to root, so prepend characters.

Interview Explanation
#

During DFS I prepend each node’s character, so at a leaf the string reads leaf to root, and I keep the smallest. Time O(n · h).

Related

LeetCode 113: Path Sum II
·2 mins
LeetCode Medium Backtracking Tree Depth-First-Search Binary-Tree
LeetCode 113 note: backtrack with the current path and store a copy at a leaf whose total matches; values can be negative, so no early pruning
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts
LeetCode 606: Construct String from Binary Tree
·1 min
LeetCode Medium String Tree Depth-First-Search Binary-Tree
LeetCode 606 note: output in pre-order, keeping an empty () when only the left subtree is missing, and omitting the right parentheses when it is empty
LeetCode 257: Binary Tree Paths
·1 min
LeetCode Easy String Backtracking Tree Depth-First-Search
LeetCode 257 note: DFS carrying the path string down, adding the whole path at each leaf
LeetCode 116: Populating Next Right Pointers in Each Node
·2 mins
LeetCode Medium Linked-List Tree Depth-First-Search Breadth-First-Search
LeetCode 116 note: in a perfect binary tree, walk each level through the next pointers already set on the level above: left.next = right and right.next = next.left, with O(1) extra space
LeetCode 129: Sum Root to Leaf Numbers
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Tree
LeetCode 129 note: on the way down multiply the current number by 10 and add the node’s value, adding it to the total at a leaf