class Node:
    def __init__(self, val=0):
        self.val = val
        self.left = None
        self.right = None


def deserialize(data):
    nodes = []
    for d in data:
        nodes.append(Node(d) if d is not None else None)
    # nodes = [Node[d] or None for d in data]
    # print(nodes)
    size = len(nodes)
    # print(size)

    for i, n in enumerate(nodes):
        if n is None:
            continue
        if 2 * i + 1 < size:
            n.left = nodes[2 * i + 1]
        if 2 * i + 2 < size:
            n.right = nodes[2 * i + 2]

    return nodes[0]


def serialize(t, string=False):
    q = [t]
    res = []

    while q:
        node = q.pop()
        if node is not None:
            res.append(node.val)
            q.insert(0, node.left)
            q.insert(0, node.right)
        else:
            res.append(None)

    while res[-1] is None:
        res.pop()

    if not string:
        return res
    else:
        return ",".join(map(lambda x: str(x) if x is not None else "null", res))


def deserialize2(data):
    if not data:
        return None

    root = Node(data[0])
    nodes = [root]
    i = 1
    while i < len(data):
        node = nodes.pop()
        node.left = Node(data[i]) if data[i] is not None else None
        node.right = Node(data[i + 1]) if data[i + 1] is not None else None
        i += 2

        if node.left is not None:
            nodes.insert(0, node.left)
        if node.right is not None:
            nodes.insert(0, node.right)

    return root


t = deserialize2([1, 2, 3, None, None, 6, 7, None, None, 12, 13])

s = serialize(t)

print(s)

