Smallest String Starting From Leaf — LeetCode 988 Python Solution
- Problem
- #988
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 988. Smallest String Starting From Leaf is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 988. Smallest String Starting From Leaf?
- LeetCode 988. Smallest String Starting From Leaf is rated Medium on LeetCode.
- What topics does LeetCode 988. Smallest String Starting From Leaf cover?
- LeetCode 988. Smallest String Starting From Leaf is tagged Tree, Depth-First Search, String, Backtracking and Binary Tree on LeetCode.