Lintcode - Serialization and Deserialization Of Binary Tree

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.

注意這裏是BFS,而且每個token之間用“ ”分割。

    public String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int last = 1;
        StringBuilder result = new StringBuilder();
        result.append(root.val);
        while (!queue.isEmpty()) {
            int newLast = 0;
            for (int count = 0; count < last; count++) {
                TreeNode cur = queue.poll();
                result.append(' ');
                if (cur.left != null) {
                    queue.offer(cur.left);
                    newLast++;
                    result.append(cur.left.val);
                } else {
                    result.append('#');
                }
                result.append(' ');
                if (cur.right != null) {
                    queue.offer(cur.right);
                    newLast++;
                    result.append(cur.right.val);
                } else {
                    result.append('#');
                }
            }
            last = newLast;
        }
        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) {
        TreeNode result = null;
        if (data == null || data == "#" || data.isEmpty()) {
            return result;
        }
        String[] str = data.split(" ");
        int i = 0;
        result = new TreeNode(Integer.parseInt(str[i]));
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(result);
        i++;
        int last = 1;
        while (!queue.isEmpty() && i < str.length) {
            int newLast = 0;
            for (int count = 0; count < last; count++) {
                TreeNode cur = queue.poll();
                if (str[i].equals("#")) {
                    cur.left = null;
                } else {
                    cur.left = new TreeNode(Integer.parseInt(str[i]));
                    newLast++;
                    queue.offer(cur.left);
                }
                i++;
                if (str[i].equals("#")) {
                    cur.right = null;
                } else {
                    cur.right = new TreeNode(Integer.parseInt(str[i]));
                    newLast++;
                    queue.offer(cur.right);
                }
                i++;
            }
            last = newLast;
        }
        return result;
    }


發佈了172 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章