[Swift]LeetCode1028. 从先序遍历还原二叉树 | Recover a Tree F
We run a?preorder?depth first search on the? At each node in this traversal,we output? If a node has only one child,that child is guaranteed to be the left child. Given the output? Example 1: Input: "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]
Example 2: Input: "1-2--3---4-5--6---7"
Output: [1,null,7]
Example 3: Input: "1-401--349---90--88"
Output: [1,401,349,88,90]
Note:
我们从二叉树的根节点? 在遍历中的每个节点处,我们输出? 如果节点只有一个子节点,那么保证该子节点为左子节点。 给出遍历输出? 示例 1: 输入:"1-2--3--4-5--6--7" 输出:[1,7] 示例 2: 输入:"1-2--3---4-5--6---7" 输出:[1,7] 示例 3: 输入:"1-401--349---90--88" 输出:[1,90] 提示:
Runtime:?52 ms
Memory Usage:?20.5 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 len:Int = 0 16 var s:[Character] = [Character]() 17 var pos:Int = 0 18 func recoverFromPreorder(_ S: String) -> TreeNode? { 19 len = S.count 20 s = Array(S) 21 return go(0) 22 } 23 24 func go(_ dep:Int) -> TreeNode? 25 { 26 var v:Int = 0 27 while(pos < len && s[pos] >= "0" && s[pos] <= "9") 28 { 29 v = v * 10 + (s[pos].ascii - 48) 30 pos += 1 31 } 32 var cur:TreeNode? = TreeNode(v) 33 if hasEdge(dep + 1) 34 { 35 pos += (dep + 1) 36 cur?.left = go(dep + 1) 37 } 38 if hasEdge(dep + 1) 39 { 40 pos += (dep + 1) 41 cur?.right = go(dep + 1) 42 } 43 return cur 44 } 45 46 func hasEdge(_ d:Int) -> Bool 47 { 48 if pos+d > len-1 49 { 50 return false 51 } 52 for i in pos..<(pos + d) 53 { 54 if s[i] != "-" 55 { 56 return false 57 } 58 } 59 return s[pos+d] != "-" 60 } 61 } 62 63 //Character扩展 64 extension Character 65 { 66 //Character转ASCII整数值(定义小写为整数值) 67 var ascii: Int { 68 get { 69 return Int(self.unicodeScalars.first?.value ?? 0) 70 } 71 } 72 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |