2025-08-24 16:54:22 +0000 UTC
Serialize and Deserialize BST
Categories:
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string.
"""
if root is None:
return ""
left, right = self.serialize(root.left), self.serialize(root.right)
return f"{root.val}|{len(left)}|{left}{right}"
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree.
"""
if not data:
return None
val, left_len, rest = data.split("|", 2)
root = TreeNode(int(val))
root.left = self.deserialize(rest[:int(left_len)])
root.right = self.deserialize(rest[int(left_len):])
return root
# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans