MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / Codec

Class Codec

Tree/SerializeAndDeserializeBinaryTree.py:129–220  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

127# self.right = None
128
129class Codec:
130
131 def serialize(self, root):
132 """Encodes a tree to a single string.
133
134 :type root: TreeNode
135 :rtype: str
136 """
137 if not root:
138 return None
139
140 result = []
141
142 def _serialize(roots):
143 _next = []
144 for i in roots:
145 if i:
146 result.append(i.val)
147 _next.append(i.left)
148 _next.append(i.right)
149
150 else:
151 result.append(None)
152
153 return _next
154
155 base = _serialize([root])
156
157 while any(base):
158 base = _serialize(base)
159
160 while 1:
161 if result[-1] == None:
162 result.pop()
163 else:
164 break
165
166 return str(result)
167
168
169 def deserialize(self, data):
170 """Decodes your encoded data to tree.
171
172 :type data: str
173 :rtype: TreeNode
174 """
175
176 if not data:
177 return []
178
179 data = data[1:-1].split(',')
180
181 root = TreeNode(data[0])
182
183 length = 2
184 data.pop(0)
185 leaves = [root]
186

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected