1
+ """
2
+ 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'.
3
+
4
+ Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
5
+
6
+ As a reminder, any shorter prefix of a string is lexicographically smaller.
7
+
8
+ For example, "ab" is lexicographically smaller than "aba".
9
+ A leaf of a node is a node that has no children.
10
+
11
+
12
+
13
+ Example 1:
14
+
15
+
16
+ Input: root = [0,1,2,3,4,3,4]
17
+ Output: "dba"
18
+ Example 2:
19
+
20
+
21
+ Input: root = [25,1,3,1,3,0,2]
22
+ Output: "adz"
23
+ Example 3:
24
+
25
+
26
+ Input: root = [2,2,1,null,1,0,null,0]
27
+ Output: "abc"
28
+
29
+
30
+ Constraints:
31
+
32
+ The number of nodes in the tree is in the range [1, 8500].
33
+ 0 <= Node.val <= 25
34
+ """
35
+ # Definition for a binary tree node.
36
+ # class TreeNode:
37
+ # def __init__(self, val=0, left=None, right=None):
38
+ # self.val = val
39
+ # self.left = left
40
+ # self.right = right
41
+ class Solution :
42
+ def smallestFromLeaf (self , root : Optional [TreeNode ]) -> str :
43
+ q ,result = collections .deque (),None
44
+ q .append ((root ,chr (root .val + 97 )))
45
+ while q :
46
+ node ,path = q .popleft ()
47
+ if not node .left and not node .right :
48
+ if not result :
49
+ result = path
50
+ else :
51
+ result = min (result ,path )
52
+ if node .left : q .append ((node .left ,chr (node .left .val + 97 )+ path ))
53
+ if node .right : q .append ((node .right ,chr (node .right .val + 97 )+ path ))
54
+ return result
0 commit comments