-
Notifications
You must be signed in to change notification settings - Fork 0
/
003.py
92 lines (69 loc) · 2.65 KB
/
003.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Problem:
Write a program to serialize a tree into a string and deserialize a string into a tree.
"""
from DataStructures.Queue import Queue
from DataStructures.Tree import Node, BinaryTree
def serialize_helper(node: Node) -> str:
# helper function to serialize a binary tree (uses prefix traversal)
# data is padded with single quotes (') and comma (,) is used as a delimiter
if node.right is None and node.left is None:
return f"'{node.val}','None','None'"
elif node.left is not None and node.right is None:
return f"'{node.val}',{serialize_helper(node.left)},'None'"
elif node.left is None and node.right is not None:
return f"'{node.val}','None',{serialize_helper(node.right)}"
elif node.left is not None and node.right is not None:
return (
f"'{node.val}',"
+ f"{serialize_helper(node.left)},"
+ f"{serialize_helper(node.right)}"
)
def serialize(tree: BinaryTree) -> str:
return serialize_helper(tree.root)
def deserialize_helper(node: Node, queue: Queue) -> Node:
# helper function to deserialize a string into a Binary Tree
# data is a queue containing the data as a prefix notation can be easily decoded
# using a queue
left = queue.dequeue().strip("'")
if left != "None":
# if the left child exists, its added to the tree
node.left = Node(left)
node.left = deserialize_helper(node.left, queue)
right = queue.dequeue().strip("'")
if right != "None":
# if the right child exists, its added to the tree
node.right = Node(right)
node.right = deserialize_helper(node.right, queue)
return node
def deserialize(string: str) -> BinaryTree:
# the string needs to have the same format as the binary tree serialization
# eg: data is padded with single quotes (') and comma (,) is used as a delimiter
data = string.split(",")
queue = Queue()
for node in data:
queue.enqueue(node)
tree = BinaryTree()
tree.root = Node(queue.dequeue().strip("'"))
deserialize_helper(tree.root, queue)
return tree
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node("root")
tree.root.left = Node("left")
tree.root.right = Node("right")
tree.root.left.left = Node("left.left")
print(serialize(tree))
generated_tree = deserialize(
"'root','left','left.left','None','None','None','right','None','None'"
)
print(serialize(generated_tree))
"""
SPECS:
SERIALIZE: (n = Number of Nodes)
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
DESERIALIZE: (n = Number of Characters in the String)
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""