Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
defserialize(root): ans = "" queue = collections.deque() queue.append(root) while queue: cur = queue.popleft() if cur isNone: ans += "#_" else: ans += str(cur.val) + "_" queue.append(cur.left) queue.append(cur.right) return ans[:-1]
与heap完全二叉树 的原理类似,我们知道:(起始于编号1)
已知一个节点的编号是 i,那么其左子节点就是 2 * i,右子节点就是 2 * i + 1,父节点就是 i / 2。
但是树不一定是完全二叉树。也就是我们需要解决这种问题:
但是注意,因为我们在以下代码使用的是 i 来做 increment, 所以它必定会遍历所有node,因为我们使用了queue 来存已经生成了的Node, 观察图,发现父子对应关系是正确的。
defdeserialze(self, data): if data == "#": returnNone nodes = data.split("_") ifnot nodes: returnNone root = TreeNode(int(nodes[0])) q = collections.deque() q.append(root)
i = 1
while i < len(nodes) -1 : cur = q.popleft() left = nodes[i] right = nodes[i+1] i += 2 if left != "#": l = TreeNode(int(left)) cur.left = l queue.append(l) if right != "#": r = TreeNode(int(left)) cur.right = r queue.append(r) return root
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classCodec:
defserialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ return self.serializeHelper(root)
defserializeHelper(self, root): ifnot root: return"#_" res = str(root.val) + "_" res += self.serialize(root.left) res += self.serialize(root.right) return res
defdeserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ queue = collections.deque() data = data.split("_") data = data[:-1] for i in data: queue.append(i) return self.deserializeHelper(queue)
defdeserializeHelper(self, queue): cur = queue.popleft() if cur == "#": returnNone root = TreeNode(int(cur)) root.left = self.deserializeHelper(queue) root.right = self.deserializeHelper(queue) return root
# Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classCodec:
defserialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ queue = collections.deque() queue.append(root) ans = "" while queue: cur = queue.popleft() ifnot cur: ans += "#_" else: ans += str(cur.val) + "_" queue.append(cur.left) queue.append(cur.right)
return ans[:-1] defdeserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == "#": returnNone data = data.split("_") root = TreeNode(int(data[0]))
queue = collections.deque() queue.append(root) # root has been added i = 1
while queue: cur = queue.popleft() lv = data[i] rv = data[i+1] i+= 2 if lv != "#": l = TreeNode(int(lv)) cur.left = l queue.append(l) if rv != "#": r = TreeNode(int(rv)) cur.right = r queue.append(r) return root
# Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))