Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
serialize-and-deserialize-bst.py 1.31 KB
Copy Edit Raw Blame History
Allen Liu authored 2018-10-13 13:24 +08:00 . update
# Time: O(n)
# Space: O(h)
import collections
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec(object):
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def serializeHelper(node, vals):
if node:
vals.append(node.val)
serializeHelper(node.left, vals)
serializeHelper(node.right, vals)
vals = []
serializeHelper(root, vals)
return ' '.join(map(str, vals))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def deserializeHelper(minVal, maxVal, vals):
if not vals:
return None
if minVal < vals[0] < maxVal:
val = vals.popleft()
node = TreeNode(val)
node.left = deserializeHelper(minVal, val, vals)
node.right = deserializeHelper(val, maxVal, vals)
return node
else:
return None
vals = collections.deque([int(val) for val in data.split()])
return deserializeHelper(float('-inf'), float('inf'), vals)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search