-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0988-smallest-string-starting-from-leaf.py
More file actions
42 lines (31 loc) · 1.07 KB
/
0988-smallest-string-starting-from-leaf.py
File metadata and controls
42 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# time complexity: O(n*n)
# space complexity: O(n*n)
from typing import List, Optional
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: Optional[TreeNode]) -> str:
def dfs(node: Optional[TreeNode], path: List, smallest: List[str]):
if not node:
return
path.append(chr(node.val + ord('a')))
if not node.left and not node.right:
currentString = ''.join(path[::-1])
smallest[0] = min(smallest[0], currentString)
dfs(node.left, path, smallest)
dfs(node.right, path, smallest)
path.pop()
smallest = [chr(ord('z') + 1)]
dfs(root, [], smallest)
return smallest[0]
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(3)
root.right.right = TreeNode(4)
print(Solution().smallestFromLeaf(root))