lintcode-medium-Binary Tree Serialisation

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.

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.

 

感觉方法有很多种,比如:

保存pre-order和in-order遍历得到的两个数组,再用这两个数组恢复二叉树

或者保存in-order和post-order遍历得到的两个数组,再用两个数组恢复二叉树

或者干脆直接用题里给的方法表示

/**
 * 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) {
        // write your code here
        
        if(root == null)
            return "{}";
        
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        queue.add(root);
        
        for(int i = 0; i < queue.size(); i++){
            TreeNode temp = queue.get(i);
            
            if(temp == null)
                continue;
            queue.add(temp.left);
            queue.add(temp.right);
        }
        
        while(queue.get(queue.size() - 1) == null)
            queue.remove(queue.size() - 1);
        
        StringBuilder result = new StringBuilder();
        
        result.append('{');
        result.append(queue.get(0).val);
        
        for(int i = 1; i < queue.size(); i++){
            TreeNode temp = queue.get(i);
            
            if(temp == null)
                result.append(",#");
            else
                result.append(',').append(temp.val);
        }
        result.append('}');
        return result.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.equals("{}"))
            return null;
        
        String[] value = data.substring(1, data.length() - 1).split(",");
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        queue.add(new TreeNode(Integer.parseInt(value[0])));
        int index = 0;
        boolean isLeft = true;
        
        for(int i = 1; i < value.length; i++){
            if(!value[i].equals("#")){
                TreeNode temp = new TreeNode(Integer.parseInt(value[i]));
                if(isLeft)
                    queue.get(index).left = temp;
                else
                    queue.get(index).right = temp;
                queue.add(temp);
            }
            if(!isLeft)
                index++;
            isLeft = !isLeft;
        }
        
        return queue.get(0);
    }
}

 

posted @ 2016-03-15 11:43  哥布林工程师  阅读(150)  评论(0编辑  收藏  举报