1
- """
2
- perform BFS to traverse the whole tree
3
- after we add the entire level to the string, then we go to the next level
4
-
5
- by doing this, we can always convert the serialized tree back
6
- because when you build the tree back
7
- the order doesn't matter as long as you insert each parent before child
8
- """
9
-
10
1
from collections import deque
11
2
class Codec :
12
3
def serialize (self , root ):
@@ -42,4 +33,59 @@ def deserialize(self, data):
42
33
break
43
34
else :
44
35
node = node .left
45
- return root
36
+ return root
37
+
38
+ #2020/7/13
39
+ from collections import deque
40
+ class Codec :
41
+
42
+ def serialize (self , root ):
43
+ s = ''
44
+ if not root : return s
45
+
46
+ q = deque ([root ])
47
+ while q :
48
+ node = q .popleft ()
49
+ s += str (node .val )+ ','
50
+ if node .left : q .append (node .left )
51
+ if node .right : q .append (node .right )
52
+ return s [:- 1 ]
53
+
54
+ def deserialize (self , data ):
55
+ def insert (root , node ):
56
+ if node .val <= root .val :
57
+ if not root .left :
58
+ root .left = node
59
+ else :
60
+ insert (root .left , node )
61
+ else :
62
+ if not root .right :
63
+ root .right = node
64
+ else :
65
+ insert (root .right , node )
66
+
67
+ if not data : return None
68
+
69
+ vals = [int (val ) for val in data .split (',' )]
70
+ root = TreeNode (vals [0 ])
71
+ for i in xrange (1 , len (vals )):
72
+ val = vals [i ]
73
+ insert (root , TreeNode (val ))
74
+
75
+ return root
76
+
77
+ """
78
+ Perform BFS to traverse the whole tree.
79
+ After we add the entire level to the string, then we go to the next level.
80
+
81
+ By doing this, we can always convert the serialized tree back.
82
+ Because when you build the tree back.
83
+ The order doesn't matter as long as you insert each parent before child.
84
+
85
+ For serialize(), the time and space complexity is O(N).
86
+ Because we use BFS to trverse each node once and store its val in string.
87
+
88
+ For deserialize(), the time complexity is O(NlogN).
89
+ Because we for every node, we perform insert(), which takes O(LogN) on a BST.
90
+ The space complexity is O(LogN), because the recusion will be LogN level deep.
91
+ """
0 commit comments