Tuesday, July 14, 2015

Binary Tree Serialization

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.
Have you met this question in a real interview? 
Yes

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.

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) {
        // write your code here
        StringBuffer buffer = new StringBuffer();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root != null){
             queue.offer(root);
             buffer.append(root.val);
        }
       
        while(!queue.isEmpty()){
            int size = queue.size();
            
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
               
                if(node.left == null){
                    buffer.append(",#");
                } else {
                    buffer.append(","+node.left.val);
                    queue.offer(node.left);
                }
                
                if(node.right == null){
                    buffer.append(",#");
                } else {
                    buffer.append(","+node.right.val);
                    queue.offer(node.right);
                }
            }
        }
        return buffer.toString();
    }
    
    /**
     * 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) {
        // write your code here
        if(data == null || data.length() == 0) return null;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        String[] arr = data.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
        queue.offer(root);
        for(int i = 1; i < arr.length; i++){
            TreeNode left = null, right = null;
            if(!arr[i].equals("#")){
                left = new TreeNode(Integer.parseInt(arr[i]));
            }
            if(++i < data.length() && !arr[i].equals("#")){
                right = new TreeNode(Integer.parseInt(arr[i]));
            }
            TreeNode parent = queue.poll();
            parent.left = left;
            parent.right = right;
            if(left != null)
                queue.offer(left);
            if(right != null)
                queue.offer(right);
        }
        return root;
    }
}

No comments:

Post a Comment