Implementing serialization and deserialization for a binary tree in Swift allows for efficient storage and retrieval of tree structures. Serialization converts a tree into a format that can be easily stored or transmitted, while deserialization recreates the tree from this format.
Swift, Binary Tree, Serialization, Deserialization, Data Structures
This example demonstrates how to serialize a binary tree structure into a string and deserialize it back to the original tree structure in Swift.
// Definition for a binary tree node.
class TreeNode {
var val: Int
var left: TreeNode?
var right: TreeNode?
init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Codec {
// Encodes a tree to a single string.
func serialize(_ root: TreeNode?) -> String {
var result: [String] = []
func help(_ node: TreeNode?) {
guard let node = node else {
result.append("#")
return
}
result.append(String(node.val))
help(node.left)
help(node.right)
}
help(root)
return result.joined(separator: ",")
}
// Decodes your encoded data to tree.
func deserialize(_ data: String) -> TreeNode? {
var nodes = data.split(separator: ",").map { String($0) }
func help() -> TreeNode? {
guard !nodes.isEmpty else { return nil }
let val = nodes.removeFirst()
if val == "#" {
return nil
}
let node = TreeNode(Int(val)!)
node.left = help()
node.right = help()
return node
}
return help()
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?