-
Notifications
You must be signed in to change notification settings - Fork 3
/
3_Google_Serialize_BST.py
executable file
·93 lines (71 loc) · 2.41 KB
/
3_Google_Serialize_BST.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
'''
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
'''
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right= right
def print_node(self):
print(self.data)
def print_inorder(self):
if self.left: # left exists
self.left.print_inorder()
print(self.data)
if self.right:
self.right.print_inorder()
def insert(self, data):
if (data <= self.data): # add to the left
if self.left == None: # left empty
self.left = Node(data)
else: # left exists
self.left.insert(data)
else: # add to the right
if self.right == None: # right empty
self.right = Node(data)
else: # right exists
self.right.insert(data)
def serialize(root): # using pre-order traversal -> root,left,right
serialized_tree = []
def helper(node):
if node is None: # root does not exist
return []
serialized_tree.append(node.val)
if node.left:
helper(node.left)
else:
serialized_tree.append('?')
if node.right:
helper(node.right)
else:
serialized_tree.append('?')
helper(root)
return serialized_tree
def deserialize(ls): # takes a list to construct a tree
listIter = iter(ls)
def helper():
val = next(listIter)
if val == '?':
return None
else:
node = Node(val)
node.left = helper()
node.right = helper()
return node
return helper()
if __name__ == '__main__':
#root = Node(20,Node(8),Node(22))
#root = Node(20, left= Node(8), right=Node(22))
root = Node('root', Node('left', Node('left.left')), Node('right'))
ls = serialize(root)
print(ls)
assert deserialize(serialize(root)).left.left.val == 'left.left'