Created
October 30, 2015 10:08
-
-
Save adrientetar/e6d8c20d470e004522f1 to your computer and use it in GitHub Desktop.
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 Codec: | |
def serialize(self, root): | |
"""Encodes a tree to a single string. | |
:type root: TreeNode | |
:rtype: str | |
""" | |
lst = self.serializeRecursively(root) | |
return str(lst) | |
def serializeRecursively(self, root): | |
ret = [] | |
if root is None: | |
ret.append(None) | |
return ret | |
ret.append(root.val) | |
lhs = self.serializeRecursively(root.left) | |
ret.extend(lhs) | |
rhs = self.serializeRecursively(root.right) | |
ret.extend(rhs) | |
return ret | |
def deserialize(self, data): | |
"""Decodes your encoded data to tree. | |
:type data: str | |
:rtype: TreeNode | |
""" | |
data = data.translate(None, "[ ]").split(",") | |
return self.deserializeRecursively(data) | |
def deserializeRecursively(self, data): | |
val = data.pop(0) | |
val = None | |
if val is None: | |
return val | |
ret = TreeNode(val) | |
ret.left = self.deserializeRecursively(data) | |
ret.right = self.deserializeRecursively(data) | |
return ret | |
# Your Codec object will be instantiated and called as such: | |
# codec = Codec() | |
# codec.deserialize(codec.serialize(root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment