Created
January 18, 2022 02:57
-
-
Save Semant1ka/019b90162bb5e9e612a6beca82609697 to your computer and use it in GitHub Desktop.
297. Serialize and Deserialize Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
class Codec: | |
def serialize(self, root): | |
"""Encodes a tree to a single string. | |
:type root: TreeNode | |
:rtype: str | |
""" | |
if not root: | |
return "" | |
result = [] | |
q = deque([root]) | |
while(q): | |
level_size = len(q) | |
for _ in range(level_size): | |
node = q.popleft() | |
result.append(str(node.val) if node else "null") | |
if node: | |
q.append(node.left) | |
q.append(node.right) | |
return ",".join(result) | |
def deserialize(self, data): | |
"""Decodes your encoded data to tree. | |
:type data: str | |
:rtype: TreeNode | |
""" | |
if not data: | |
return | |
tree = data.split(",") | |
root = TreeNode(val=int(tree[0])) | |
# because we won't be able to count index if we start with zero | |
# left = 2i | |
# righ = 2i+1 | |
i=1 | |
q = deque([root]) | |
while(q): | |
node = q.popleft() | |
if node: | |
left = tree[i] | |
right = tree[i+1] | |
node.left = None if left == 'null' else TreeNode(val=int(left)) | |
node.right = None if right == 'null' else TreeNode(val=int(right)) | |
q.append(node.left) | |
q.append(node.right) | |
i+=2 | |
return root | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment