Serialize and Deserialize Binary Tree

来源:互联网 发布:电极编程 编辑:程序博客网 时间:2024/06/06 00:44

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.

For example, you may serialize the following tree

    1   / \  2   3     / \    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

思路:用preorder serialization, current, left, right. 其实,想清楚很简单就是,以前的假设是数目有空,不知道怎么办。这里应该打破假设,我存的时候,建立一颗完整的树就可以了,这样需要一个字符用来表示空node,另外需要一个字符分隔符。序列化就很简单了。

反序列化,因为存的时候是一个满树,那么就按照preorder的recursion建立树就可以了。记住用queue,这样算一个点pop出来一个,这样不用计算index,很自然的建立。因为存的时候就是dfs存的,然后建立的时候,也是dfs建立的,所以有一一对应的关系。

思路2:此题还有level order的解法,稍微复杂点: http://blog.csdn.net/ljiabin/article/details/49474445

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Codec {    private String delimiter = ",";    private String emptyNode = "#";         // Encodes a tree to a single string.    public String serialize(TreeNode root) {        if(root == null) return null;        StringBuilder sb = new StringBuilder();        dfs(root, sb);        return sb.toString();    }        public void dfs(TreeNode root, StringBuilder sb){        if(root == null){            sb.append(emptyNode).append(delimiter);            return;        }        sb.append(root.val).append(delimiter);        dfs(root.left, sb);        dfs(root.right, sb);    }    // Decodes your encoded data to tree.    public TreeNode deserialize(String data) {        if(data == null || data.length() ==0) return null;        String[] splits = data.split(delimiter);        Queue<String> queue = new LinkedList<String>();        for(int i=0; i<splits.length; i++){            queue.add(splits[i]);        }        return build(queue);    }        public TreeNode build(Queue<String> queue){        if(!queue.isEmpty()){            String str = queue.poll();            if(str.equals(emptyNode)){                return null;            }            TreeNode node = new TreeNode(Integer.parseInt(str));            node.left = build(queue);            node.right = build(queue);            return node;        } else {            return null;        }    }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));


0 0