Serializing and Deserializing Binary Tree - Depth First Search / DFS on Tree

I think my solution is not better but easier to come out in a interview

def serialize(root):
    def dfs(node, str_list):
        if not node:
            str_list.append('x')
            return

        str_list.append(str(node.val))
        dfs(node.left, str_list)
        dfs(node.right, str_list)
    str_list = []
    dfs(root, str_list)
    return ' '.join(str_list)

def deserialize(s):
    idx = -1
    def dfs(s, side=None, parent_node=None):
        nonlocal idx
        idx += 1
        if idx >= len(s):
            return
        val = None if s[idx] == 'x' else int(s[idx])
        if val is None:
            return
        node = Node(val)
        if parent_node:
            if side == 'left':
                parent_node.left = node
            elif side == 'right':
                parent_node.right = node
            else:
                raise Exception("Should not be here")
        dfs(s, side='left', parent_node=node)
        dfs(s, side='right', parent_node=node)
        return node
    return dfs(s.split())

The current solution on GoLang would cause index out of bound error while deserializing. We must add

if index >= len(nodes) {
      return nil
}

before

val := nodes[index]