Description
Problem Number,
Serialize and Deserialize Binary Tree
Bug Description
The current implementation of deserialize()
incorrectly creates children for nodes that should not exist, resulting in an invalid binary tree structure. Specifically, it allows nodes to be attached under null
parents, which violates the definition of a binary tree.
Surprisingly, my test cases are still passing, which suggests the issue is not being caught by typical serialization-deserialization checks.
For example, with the input:
[1,2,3,null,null,4,5,6,7]
My code constructs nodes 6
and 7
as children of what should be a null
node — something that should not be possible in a valid binary tree. This highlights a flaw in the deserialization logic that assumes a complete binary tree structure and doesn't properly respect null
entries.
Language Used for Code
Python/Python3
Code used for Submit/Run operation
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return ""
q = deque([root])
strl = []
while q:
n = q.popleft()
if n != None:
q.append(n.left)
q.append(n.right)
strl.append(str(n.val))
else:
strl.append("null")
return ",".join(strl)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data:
return
ndata = data.split(",")
def dfs(pos):
if pos >= len(ndata):
return None
node = TreeNode(ndata[pos])
node.left = dfs(2 * pos + 1)
node.right = dfs(2 * pos + 2)
return node
return dfs(0)
Expected behavior
A proper deserialization should respect "null" entries as missing nodes and avoid generating children under those positions and properly check if resulting binary tree matches the original one.