Skip to content

Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Approach

Use level order traversal and use "#" if the child node is null

class Codec() {
    // Encodes a URL to a shortened URL.
    fun serialize(root: TreeNode?): String {
        val encoded = StringBuilder()

        val queue = ArrayDeque<TreeNode>()
        root?.let{
            queue.add(it)
            encoded.append(it.`val`)
            encoded.append(",")
        }

        while(queue.isNotEmpty()) {
            val node = queue.removeFirst()
            node.left?.let {
                queue.add(it)
                encoded.append(it.`val`)
            } ?: encoded.append("#")
            encoded.append(",")

            node.right?.let {
                queue.add(it)
                encoded.append(it.`val`)
            } ?: encoded.append("#")
            encoded.append(",")
        }

        return encoded.trim(',').toString()
    }

    // Decodes your encoded data to tree.
    fun deserialize(data: String): TreeNode? {
        if(data.isEmpty()) return null

        val stack = ArrayDeque<TreeNode>()

        val values = data.split(",")
        val root = TreeNode(values[0].toInt())
        stack.addFirst(root)

        var i = 1
        while(i < values.size) {
            val node = stack.removeFirst()
            if(values[i] == "#") {
                node.left = null
            } else {
                node.left = TreeNode(values[i].toInt())
                stack.add(node.left!!)
            }
            i++

            if(values[i] == "#") {
                node.right = null
            } else {
                node.right = TreeNode(values[i].toInt())
                stack.add(node.right!!)
            }
            i++
        }


        return root
    }
}