题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self) -> None: self.index = 0 self.s = '' def func1(self, root): if not root: self.s += '#' return self.s += str(root.val) + '!' self.func1(root.left) self.func1(root.right) def Serialize(self, root): self.s = '' if not root: return '#' self.func1(root) return self.s def func2(self, s): if self.index >= len(s) or s[self.index] == '#': self.index += 1 return None num = 0 while s[self.index] != '!' or self.index >= len(s): num = num*10 + int(s[self.index]) self.index += 1 node = TreeNode(num) if self.index == len(s): return node else: self.index += 1 node.left = self.func2(s) node.right = self.func2(s) return node def Deserialize(self, s): if s == '#': return None return self.func2(s)