lintcode7- Binary Tree Serialization- medium

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'.

 Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.

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(queue)来序列化以及反序列化。用“#”来标记null节点,用“,”来做split分割。

1. queue也能插入null。会被记录下来

2.要给一个String不断粘小String上去的时候,用StringBuilder效率会更高。sb.append(); sb.toString;

3.string.split(",")会返回一个String[],其中有被这个符号分割开的subString

4.切记要用string.equals("#")来对比是否相等!不可以string == "#",每次"#"都是弄了一个新的字符串,比不出来的,只会返回你false

参考答案写的步骤更分明,值得学习

1.自己实现

/**
 * 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;
 *     }
 * }
 */


public 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
        // string 初始化方式?
        String result = new String();
        if (root == null) {
            return result;
        }
        
        TreeNode emptyNode = new TreeNode(0);
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == emptyNode) {
                result = result + "#" + ",";
                continue;
            }
            result = result + node.val + ",";
            if (node.left != null) {
                queue.offer(node.left);
            } else {
                queue.offer(emptyNode);
            }
            if (node.right != null) {
                queue.offer(node.right);
            } else {
                queue.offer(emptyNode);
            }
        }
        
        return result;
    }

    /**
     * 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[] strings = data.split(",");
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        // 0: not done; 1: left done, right not done; 2: both done;
        Map<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();
        TreeNode root = new TreeNode(Integer.parseInt(strings[0]));
        
        queue.offer(root);
        TreeNode parent = null;
        
        for (int i = 1; i < strings.length; i++) {

            if (parent == null) {
                parent = queue.poll();
                map.put(parent, 0);
            }
            
            if (strings[i].equals("#")) {
                if (map.get(parent) == 0) {
                    map.put(parent,1);
                } else {
                    parent = null;
                }
                
            } else {
                TreeNode node = new TreeNode(Integer.parseInt(strings[i]));
                queue.offer(node);
                if (map.get(parent) == 0) {
                    parent.left = node;
                    map.put(parent, 1);
                } else {
                    parent.right = node;
                    parent = null;
                }
            }
        }
        
        return root;
    }
}

2.九章代码

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) {
        if (root == null) {
            return "{}";
        }

        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        queue.add(root);

        for (int i = 0; i < queue.size(); i++) {
            TreeNode node = queue.get(i);
            if (node == null) {
                continue;
            }
            queue.add(node.left);
            queue.add(node.right);
        }

        while (queue.get(queue.size() - 1) == null) {
            queue.remove(queue.size() - 1);
        }

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(queue.get(0).val);
        for (int i = 1; i < queue.size(); i++) {
            if (queue.get(i) == null) {
                sb.append(",#");
            } else {
                sb.append(",");
                sb.append(queue.get(i).val);
            }
        }
        sb.append("}");
        return sb.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) {
        if (data.equals("{}")) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        queue.add(root);
        int index = 0;
        boolean isLeftChild = true;
        for (int i = 1; i < vals.length; i++) {
            if (!vals[i].equals("#")) {
                TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
                if (isLeftChild) {
                    queue.get(index).left = node;
                } else {
                    queue.get(index).right = node;
                }
                queue.add(node);
            }
            if (!isLeftChild) {
                index++;
            }
            isLeftChild = !isLeftChild;
        }
        return root;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7722896.html