-
Notifications
You must be signed in to change notification settings - Fork 0
/
DCP-3-20190217.py
85 lines (70 loc) · 2.14 KB
/
DCP-3-20190217.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
"""
This problem was asked by Google.
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'
"""
from json import loads, dumps, JSONDecoder
class Node:
class JSONDecodeNodeTree:
pass
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return self.__str__()
def __str__(self):
return self.val
@staticmethod
def deserialize(serialized_tree):
return loads(serialized_tree)
@property
def binaries(self):
return self.left, self.right
@property
def hierarchy(self):
n = 0
hierarchy = {n: (self.val, )}
queue = [self.binaries]
while queue:
n += 1
hierarchy[n] = list()
enqueue = list()
for binaries in queue:
if binaries != (None, None):
hierarchy[n].append(binaries)
enqueue.extend([node.binaries for node in binaries if node])
queue = enqueue
return hierarchy
@property
def serialized(self):
return dumps(str(self.hierarchy))
node = Node('root', left=Node('left', left=Node('left.left')), right=Node('right', left=Node("right.left"), right=Node("right.right")))
print(node.serialized)
print(Node.deserialize(node.serialized))
"""
tree:
root
|
left-----right
|
left---
"""
# def serialize(root):
# def get_nodes(node):
# return {'val': node.val, 'left': node.left, 'right': node.right}
# n = 0
# hierarchy = {n: root}
# node = root
# while node.left or node.right:
# n += 1
# hierarchy[n] = {'left': node}