func serialize(root: TreeNode) -> String {
var result = ""
var queue: [TreeNode?] = [root]
while queue.isEmpty == false {
if let first = queue.first, let node = first {
result.append((result.isEmpty ? "\(node.val)" : ",\(node.val)"))
queue.append(node.left)
queue.append(node.right)
}
else {
result.append(",null")
}
queue.removeFirst()
}
return result
}
3.2 解码
func deserialize(data: String) -> TreeNode? {
let array: [String] = data.components(separatedBy: ",")
var nodes: [TreeNode?] = []
array.forEach { item in
if let v = Int(item) {
nodes.append(TreeNode(v))
}
else {
nodes.append(nil)
}
}
if nodes.isEmpty == true { return nil }
var queue: [TreeNode] = []
var index = 0
if let f = nodes.first, let n = f {
queue.append(n)
}
while queue.isEmpty == false {
if let node = queue.first, index + 1 < nodes.count, index + 2 < nodes.count {
node.left = nodes[index + 1]
node.right = nodes[index + 2]
if let l = node.left {
queue.append(l)
}
if let r = node.right {
queue.append(r)
}
index += 2
}
queue.removeFirst()
}
return nodes.first ?? nil
}
3.3 测试用例
let root1 = TreeNode(1)
let root2 = TreeNode(2)
let root3 = TreeNode(3)
let root4 = TreeNode(4)
let root5 = TreeNode(5)
root1.left = root2
root1.right = root3
root3.left = root4
root3.right = root5
// 编码
let s1 = serialize(root: root1)
// 解码
let node = deserialize(data: s1)
// 再编码验证
if let n = node {
serialize(root: n)
}