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

Solution:

Serialize:

  1. using an arraylist to hold all treeNodes
  2. add root first, the traverse while (arraylist is not empty)
  3. remove all the null node at the end
  4. transform the arraylist of treenodes into string

Deserialize:

  1. Using an arraylist to keep track of the parent node, add the root first, idx = 0, leftchild = true;
  2. starting from the first child node, traverse all the nodes
    1. if it's left child, update parent.left
    2. if it's right child, update parent.right
      1. idx ++ ----> go to next parent node
    3. add the child node to parent node arraylist
    4. leftchild = !leftchul
public String serialize(TreeNode root) {

        if(root == null){
            return "[]";
        }

        ArrayList<TreeNode> q = new ArrayList<TreeNode>();

        q.add(root);
        for(int i = 0; i < q.size(); i++){
                TreeNode curr = q.get(i);
                if(curr == null){
                    continue;
                }else{
                    q.add(curr.left);
                    q.add(curr.right);
                }
        }
        while(q.get(q.size() - 1) == null){
            q.remove(q.size() -1);
        }
        StringBuilder res = new StringBuilder();
        res.append("[");
        res.append(q.get(0).val);

        for(int i = 1; i < q.size(); i++){
            if(q.get(i) == null){
                res.append(",null");
            }else{
                res.append(",");
                res.append(q.get(i).val);
            }
        }
        res.append("]");
        return res.toString();
    }



    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.length() <= 2){
            return null;
        }    
        String s = data.substring(1,data.length() -1);
        String[] arr = s.split(",");
        int len = arr.length;

        if(arr[0].equals("")){
            return new TreeNode(Integer.parseInt(s));
        }
        TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
        int j = 0;
        ArrayList<TreeNode> tmp = new ArrayList<TreeNode>();
        tmp.add(root);
        boolean left = true;
        for(int i = 1; i < len; i++){

            if(!arr[i].equals("null")){
                TreeNode add = new TreeNode(Integer.parseInt(arr[i]));
                if(left){
                    tmp.get(j).left = add;    
                }else{
                    tmp.get(j).right = add;
                }
                tmp.add(add);
            }

                if(!left){
                    j++;
                }

                left = !left;
        }


        return root;
    }

results matching ""

    No results matching ""