public String serialize(TreeNode root) {
        // write your code here
        if (root == null) return "{}";
        Queue<TreeNode> q = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        q.add(root);
        sb.append("{");

        while (!q.isEmpty()) {
           TreeNode t = q.poll();
          if(t!=null){
            sb.append(String.valueOf(t.val) + ",");
            q.add(t.left);
            q.add(t.right);
          }else{
            sb.append("#,");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
         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) {
        // write your code here
        if (data.equals("{}")) {
            return null;
        }
        String[] arr = data.substring(1, data.length() - 1).split(",");
    TreeNode root = new TreeNode(Integer.parseInt(arr[0]));

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

    int i=1;
    while(!queue.isEmpty()){
        TreeNode t = queue.poll();

        if(t==null)
            continue;

        if(!arr[i].equals("#")){
            t.left = new TreeNode(Integer.parseInt(arr[i]));    
            queue.offer(t.left);

        }else{
            t.left = null;
            queue.offer(null);
        }
        i++;

        if(!arr[i].equals("#")){
            t.right = new TreeNode(Integer.parseInt(arr[i]));    
            queue.offer(t.right);

        }else{
            t.right = null;
            queue.offer(null);
        }
        i++;
    }
        return root;
    }

results matching ""

    No results matching ""