Here is my code to serialize and deserialize binary tree, which may have a lot of empty nodes. I am written in Python 2.7. Any advice on performance improvement in terms of algorithm time complexity, bugs or code style advice is appreciated.
My major idea is, serialize only non-empty nodes, with node ID information, where left node ID * 2 = parent node ID
, and right node ID * 2 + 1 = parent node ID
Source code in Python 2.7,
from collections import defaultdict
class TreeNode:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def serialize_tree(self, result):
stack = []
stack.append((self, 1))
while len(stack) > 0:
node, index = stack.pop(0)
result.append((node.value, index))
if node.left:
stack.append((node.left, index*2))
if node.right:
stack.append((node.right, index*2+1))
@staticmethod
def deserialize_tree(source):
result = []
for (node_value, index) in source:
node = TreeNode(node_value, None, None)
result.append(node)
if index == 1:
continue
elif index % 2 == 0:
result[index / 2 - 1].left = node
else:
result[(index - 1) / 2 - 1].right = node
return result[0]
def print_tree(self, result):
result.append(self.value)
if self.left:
self.left.print_tree(result)
else:
result.append('#')
if self.right:
self.right.print_tree(result)
else:
result.append('#')
if __name__ == "__main__":
root = TreeNode(1, TreeNode(2, None, TreeNode(4, None, None)), TreeNode(3, None, None))
result = []
root.serialize_tree(result)
print result
new_root = TreeNode.deserialize_tree(result)
result2 = []
new_root.print_tree(result2)
print result2