I am trying to write code for serializing and deserializing a binary tree. I was successfully able to serialize the tree, however, I find it difficult to deserialize. (I am aware that many solutions are available. However, I prefer to learn on my own before I look them up)
Consider the tree below
__1
/ \
2 3
/ \ \
4 5 6
My serialization module outputs
[1, 2, 4, None, None, 5, None, None, 3, None, 6, None, None]
My code for the same is
def serialize(root):
nodes = list()
stack = [root]
while len(stack):
node = stack.pop()
if node is not None:
nodes.append(node.value)
if node.right:
stack.append(node.right)
else:
nodes.append(None)
if node.left:
stack.append(node.left)
else:
nodes.append(None)
return nodes
- How do I deserialize without recursion?
- Is there a recursive version of the deserialization?
- The tree traversal I did, does it have a name?
- Is there a recursive version of the serialization?
Any pointers to helpful material are also appreciated.