import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    String Serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        Queue<TreeNode> queue = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        TreeNode cur = root;
        queue.offer(cur);
        while (!queue.isEmpty()) {
            cur = queue.poll();
            sb.append(cur.val + "_");
            if (cur.val != -1) {
                queue.offer(cur.left != null ? cur.left : new TreeNode(-1));
                queue.offer(cur.right != null ? cur.right : new TreeNode(-1));
            }
        }
        return sb.toString();
    }
    TreeNode Deserialize(String str) {
       if (str.equals("")) {
        return null;
       }
       String[] parts = str.split("_");
       int n = parts.length;
       TreeNode root = new TreeNode(Integer.parseInt(parts[0]));
       Queue<TreeNode> queue = new LinkedList<>();
       TreeNode cur = root;
       queue.offer(cur);
       for (int i = 1; i < n - 1; i += 2) {
         cur = queue.poll();
         int left = Integer.parseInt(parts[i]);
         int right = Integer.parseInt(parts[i + 1]);
         if (left != -1) {
            cur.left = new TreeNode(left);
            queue.offer(cur.left);
         }
         if (right != -1) {
            cur.right = new TreeNode(right);
            queue.offer(cur.right);
         }
       }
       return root;
    }
}