1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Codec { func serialize(_ root: Node?) -> String { guard let root = root else { return "$" } var s = "\(root.val),\(root.children.count)," for child in root.children { s += serialize(child) } return s }
func deserialize(_ data: String) -> Node? { let arr = data.components(separatedBy: ",").compactMap { Int($0) }; var i = 0 func deserialize() -> Node? { if i >= arr.count { return nil } let n = Node(arr[i]) i += 2; for _ in 0..<arr[i-1] { if let a = deserialize() { n.children.append(a) } } return n } return deserialize() } }
|