/*
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode (int x)
    {
        val = x;
    }
}*/
using System.Text;
using System.Collections.Generic;

class Solution
{
    public string Serialize(TreeNode root)
    {
        StringBuilder res = new StringBuilder();
        Queue<TreeNode> que = new Queue<TreeNode>();
        que.Enqueue(root);
        while(que.Count != 0){
            for(int i = que.Count; i > 0; i--){
                TreeNode cur = que.Dequeue();
                if(cur == null){
                    res.Append("#,");
                    continue;
                }
                res.Append(cur.val);
                res.Append(",");
                que.Enqueue(cur.left);
                que.Enqueue(cur.right);
            }
        }
        res.Remove(res.Length - 1, 1);
        return res.ToString();
    }
    public TreeNode Deserialize(string str)
    {
        if(str == "#") return null;
        string[] strs = str.Split(',');
        TreeNode root = new TreeNode(int.Parse(strs[0]));
        Queue<TreeNode> que = new Queue<TreeNode>();
        que.Enqueue(root);
        int ord = 1;
        while(que.Count != 0){
            for(int i = que.Count; i > 0; i--){
                TreeNode cur = que.Dequeue();
                if(strs[ord] != "#") {
                    cur.left = new TreeNode(int.Parse(strs[ord]));
                    que.Enqueue(cur.left);
                }
                ord++;
                if(strs[ord] != "#") {
                    cur.right = new TreeNode(int.Parse(strs[ord]));
                    que.Enqueue(cur.right);
                }
                ord++;
            }
        }
        return root;
    }
}