How do I implement the serialize and deserialize a binary tree in Swift?

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() } }

Swift Binary Tree Serialization Deserialization Data Structures