Skip to content

Commit b5c2501

Browse files
authored
Create smallest-string-starting-from-leaf.py
1 parent 0440fbc commit b5c2501

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n + l * h), l is the number of leaves
2+
# Space: O(h)
3+
4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, x):
7+
self.val = x
8+
self.left = None
9+
self.right = None
10+
11+
12+
class Solution(object):
13+
def smallestFromLeaf(self, root):
14+
"""
15+
:type root: TreeNode
16+
:rtype: str
17+
"""
18+
def dfs(node, candidate, result):
19+
if not node:
20+
return
21+
22+
candidate.append(chr(ord('a') + node.val))
23+
if not node.left and not node.right:
24+
result[0] = min(result[0], "".join(reversed(candidate)))
25+
dfs(node.left, candidate, result)
26+
dfs(node.right, candidate, result)
27+
candidate.pop()
28+
29+
result = ["~"]
30+
dfs(root, [], result)
31+
return result[0]

0 commit comments

Comments
 (0)