【leetcode】Serialize&Deserialize Binary Tree (Java)

Serialize and Deserialize Binary Tree

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.

题意大致就是把这个二叉树结构序列化和反序列化。

解题思路:

就是可以按照很简单的方法,每个val后面加一个字母x表示结束,按照一定的顺序把二叉树组成一个String,然后再解析成原来的结构。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        LinkedList<TreeNode> temp = new LinkedList<TreeNode>();
        temp.add(root);
        StringBuilder result = new StringBuilder();
        
        while(!temp.isEmpty()){
            TreeNode current = temp.removeFirst();
            if(current==null)
                result.append("nx");
            else{
                temp.add(current.left);
                temp.add(current.right);
                result.append(current.val + "x");
            }
        }
        return result.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] res = data.split("x"); 
        ArrayList<TreeNode> current = new ArrayList<TreeNode>();
        
        if(res[0].equals("n"))
            return null;
        else{
            for(int i = 0; i < res.length; i++){
                if(res[i].equals("n")){
                    current.add(null);
                }else{
                    current.add(new TreeNode(Integer.parseInt(res[i])));
                }
            }
        }
        int nullNum = 0;
        for(int i = 0; i < current.size(); i++){
            if(current.get(i)!=null){
                current.get(i).left = current.get(2*i + 1 - nullNum*2);
                current.get(i).right = current.get(2*i + 2 - nullNum*2);
            }
            else{
                nullNum++;
            }
        }
        return current.get(0);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

需要注意的几点:

  1. 设计好如何存储和用什么办法解析String,这方面自己设计好就行

  2. 这里的二叉树并不是完全二叉树,左右子节点的下标不遵循2*i+1和2*i+2;按照我的编码方式,在这个String中,此节点前面的null节点,每个下面都应该有2个null左右子节点的缺漏,所以在原有基础(2*i+1和2*i+2)上减去缺漏的 2*该节点前null节点数,就可以得到左右子节点了。

  3. 我最开始没有使用StringBulider,用的是String= String+String形式,然后就很杯具的一直无法通过,搞了好长时间。如何编写有效率的Java代码,是我的很严重的问题。。。


你可能感兴趣的:(java,LeetCode)