You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassCodec:
defserialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str """ret= []
defpre_order(root):
ifroot:
ret.append(root.val)
pre_order(root.left)
pre_order(root.right)
pre_order(root)
return" ".join(map(str, ret))
defdeserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode """vals=deque(map(int, data.split()))
defbuild(min_val, max_val):
ifvalsandmin_val<vals[0] <max_val:
cur_val=vals.popleft()
node=TreeNode(cur_val)
node.left=build(min_val, cur_val)
node.right=build(cur_val, max_val)
returnnodereturnNonereturnbuild(-float("inf"), float("inf"))
# Your Codec object will be instantiated and called as such:# ser = Codec()# deser = Codec()# tree = ser.serialize(root)# ans = deser.deserialize(tree)# return ans