Binary Tree Serialization

Source

Design an algorithm and write code to serialize and
deserialize a binary tree. Writing the tree to a file
is called 'serialization' and reading back from the
file to reconstruct the exact same binary tree is 'deserialization'.

There is no limit of how you deserialize or serialize
a binary tree, you only need to make sure you can
serialize a binary tree to a string and deserialize
this string to the original structure.

Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

  3
 / \
9  20
  /  \
 15   7
Our data serialization use bfs traversal. This is
just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

Python

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:

    '''
    @param root: An object of TreeNode, denote the root of the binary tree.
    This method will be invoked first, you should design your own algorithm 
    to serialize a binary tree which denote by a root node to a string which
    can be easily deserialized by your own "deserialize" method later.
    '''
    def serialize(self, root):
        # write your code here
        data=[]
        self.buildString(root, data)
        return ''.join(data)

    def buildString(self, root, data):
        if root is None:
            data.append("#,")
            return
        data.append(str(root.val))
        data.append(",")
        self.buildString(root.left, data)
        self.buildString(root.right, data)
    '''
    @param data: A string serialized by your serialize method.
    This method will be invoked second, the argument data is what exactly
    you serialized at method "serialize", that means the data is not given by
    system, it's given by your own serialize method. So the format of data is
    designed by yourself, and deserialize it here as you serialize it in 
    "serialize" method.
    '''
    def deserialize(self, data):
        # write your code here
        nodes = data.split(",")
        return self.buildTree(nodes)

    def buildTree(self, nodes):
        node = nodes.pop(0)
        if node=="#":
            return None
        root = TreeNode(int(node))
        root.left = self.buildTree(nodes)
        root.right = self.buildTree(nodes)
        return root

Java

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
class Solution {
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    public String serialize(TreeNode root) {
        StringBuilder data = new StringBuilder();
        buildString(root, data);
        return data.toString();
    }

    public void buildString(TreeNode root, StringBuilder data){
        if(root==null){
            data.append("#,");
            return;
        }
        data.append(root.val).append(",");
        buildString(root.left, data);
        buildString(root.right, data);
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
        LinkedList<String> nodes = new LinkedList<String>();
        nodes.addAll(Arrays.asList(data.split(",")));
        return buildTree(nodes);
    }

    public TreeNode buildTree(LinkedList<String> nodes){
        String node = nodes.remove();
        if(node.equals("#")){
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(node));
        root.left = buildTree(nodes);
        root.right = buildTree(nodes);
        return root;
    }
}