classCodec{ funcencode(_root: Node?) -> TreeNode? { guardlet root = root else { returnnil } let tn =TreeNode(root.val); var p: TreeNode? = tn iflet n = root.children.first { p?.left = encode(n); p = p?.left for n in root.children[1...] { p?.right = encode(n); p = p?.right } } return tn }
funcdecode(_root: TreeNode?) -> Node? { guardlet root = root else { returnnil } let n =Node(root.val); var p = root.left iflet l = decode(p) { n.children.append(l) } whilelet q = p?.right, let r = decode(q) { n.children.append(r); p = q } return n } }
classCodec{ funcserialize(_root: Node?) -> String { guardlet root = root else { return"$" } var s ="\(root.val),\(root.children.count)," for child in root.children { s += serialize(child) } return s }
funcdeserialize(_data: String) -> Node? { let arr = data.components(separatedBy: ",").compactMap { Int($0) }; var i =0 funcdeserialize() -> Node? { if i >= arr.count { returnnil } let n =Node(arr[i]) i +=2; for_in0..<arr[i-1] { iflet a = deserialize() { n.children.append(a) } } return n } return deserialize() } }