#988
Smallest String Starting From Leaf
MediumStringBacktrackingTreeDepth-First SearchBinary TreeDepth-First SearchBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can still use DFS, but we will maintain the path in reverse order and use a stack to build the strings as we backtrack. This way, we can directly compare strings without needing to construct them multiple times.
⚙️
Algorithm
3 steps- 1Step 1: Use a stack to perform a depth-first search (DFS) on the tree.
- 2Step 2: Maintain a string that builds up as we traverse down the tree.
- 3Step 3: When a leaf is reached, compare the current string with the smallest string found so far and update if necessary.
solution.py20 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def smallestFromLeaf(self, root: TreeNode) -> str:
9 self.min_string = None
10 def dfs(node, path):
11 if not node:
12 return
13 path = chr(node.val + 97) + path
14 if not node.left and not node.right:
15 if self.min_string is None or path < self.min_string:
16 self.min_string = path
17 dfs(node.left, path)
18 dfs(node.right, path)
19 dfs(root, '')
20 return self.min_stringℹ
Complexity note: The time complexity is O(n) because we visit each node once, and the space complexity is O(n) due to the recursion stack.
- 1The lexicographical order is crucial; always compare strings at leaf nodes.
- 2Using DFS allows us to explore all paths efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.