defserialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ res = [] defdfs(node): nonlocal res ifnot node: res.append("") else: res.append(str(node.val)) dfs(node.left) dfs(node.right) dfs(root) return",".join(res)
defdeserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ data = data.split(",") defdfs(data): val = data.pop(0) if val == "": returnNone node = TreeNode(int(val)) node.left = dfs(data) node.right = dfs(data) return node return dfs(data)