Created
September 1, 2019 06:38
-
-
Save santhalakshminarayana/3c6f5b9e93285fabc0c5864558b0a614 to your computer and use it in GitHub Desktop.
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.
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
# Definition for a binary tree node. | |
# class TreeNode(object): | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
class Serialize_To_Deserialize: | |
def serialize(self, root): | |
"""Encodes a tree to a single string. | |
:type root: TreeNode | |
:rtype: str | |
""" | |
from collections import deque | |
if root is None: | |
return "" | |
qu=deque() | |
data=[] | |
qu.appendleft(root) | |
while len(qu)>0: | |
node=qu.pop() | |
if node is None: | |
data.append("$") | |
continue | |
else: | |
data.append(str(node.val)) | |
qu.appendleft(node.left) | |
qu.appendleft(node.right) | |
return ' '.join(data) | |
def deserialize(self, data): | |
"""Decodes your encoded data to tree. | |
:type data: str | |
:rtype: TreeNode | |
""" | |
from collections import deque | |
if len(data) is 0: | |
return None | |
vals=iter(data.split()) | |
root=TreeNode(int(next(vals))) | |
qu=deque() | |
qu.appendleft(root) | |
while len(qu)>0: | |
node=qu.pop() | |
left=next(vals) | |
right=next(vals) | |
if left is not '$': | |
new_node=TreeNode(int(left)) | |
node.left=new_node | |
qu.appendleft(new_node) | |
else: | |
node.left=None | |
if right is not '$': | |
new_node=TreeNode(int(right)) | |
node.right=new_node | |
qu.appendleft(new_node) | |
else: | |
node.right=None | |
return root | |
# std = Serialize_To_Deserialize() | |
# std.deserialize(std.serialize(root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment