1. 程式人生 > >[Swift Weekly Contest 122]LeetCode988. 從葉結點開始的最小字符串 | Smallest String Starting From Leaf

[Swift Weekly Contest 122]LeetCode988. 從葉結點開始的最小字符串 | Smallest String Starting From Leaf

start div elf code out 示例 sta binary 1-1

Given the root of a binary tree, each node has a value from 0 to 25 representing the letters ‘a‘ to ‘z‘: a value of 0 represents ‘a‘, a value of 1 represents ‘b‘, and so on.

Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

(As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab"

is lexicographically smaller than "aba". A leaf of a node is a node that has no children.)

Example 1:

技術分享圖片

Input: [0,1,2,3,4,3,4]
Output: "dba"

Example 2:

技術分享圖片

Input: [25,1,3,1,3,0,2]
Output: "adz"

Example 3:

技術分享圖片

Input: [2,2,1,null,1,0,null,0]
Output: "abc"

Note:

  1. The number of nodes in the given tree will be between 1
    and 1000.
  2. Each node in the tree will have a value between 0 and 25.

給定一顆根結點為 root 的二叉樹,書中的每個結點都有一個從 025 的值,分別代表字母 ‘a‘‘z‘:值 0 代表 ‘a‘,值 1 代表 ‘b‘,依此類推。

找出按字典序最小的字符串,該字符串從這棵樹的一個葉結點開始,到根結點結束。

(小貼士:字符串中任何較短的前綴在字典序上都是較小的:例如,在字典序上 "ab""aba" 要小。葉結點是指沒有子結點的結點。)

示例 1:

技術分享圖片

輸入:[0,1,2,3,4,3,4]
輸出:"dba"

示例 2:

技術分享圖片

輸入:[25,1,3,1,3,0,2]
輸出:"adz"

示例 3:

技術分享圖片

輸入:[2,2,1,null,1,0,null,0]
輸出:"abc"

提示:

  1. 給定樹的結點數介於 11000 之間。
  2. 樹中的每個結點都有一個介於 025 之間的值。

Runtime: 24 ms Memory Usage: 3.8 MB
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var ret:String = "~"
16     func smallestFromLeaf(_ root: TreeNode?) -> String {
17         dfs(root,"")
18         return ret
19     }
20         
21     func dfs(_ cur: TreeNode?,_ s: String)
22     {
23         var s = s
24         if cur == nil {return}
25         s = String((97 + cur!.val).ASCII) + s
26         if cur?.left == nil && cur?.right == nil
27         {
28             if s < ret {ret = s}
29         }
30         dfs(cur?.left, s)
31         dfs(cur?.right, s)
32     }
33 }
34     
35 //Int擴展方法  
36 extension Int
37 {
38     //屬性:ASCII值(定義大寫為字符值)
39     var ASCII:Character 
40     {
41         get {return Character(UnicodeScalar(self)!)}
42     }
43 }

[Swift Weekly Contest 122]LeetCode988. 從葉結點開始的最小字符串 | Smallest String Starting From Leaf