题目要求要用'#'代表空值
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution:
def Serialize(self, root) -> str:
# write code here
if not root:
return '#'
q = queue.Queue()
res = []
q.put(root)
while not q.empty():
temp = q.get()
if temp:
res.append(str(temp.val))
q.put(temp.left)
q.put(temp.right)
else:
res.append('#')
continue
print(','.join(res))
return ','.join(res)
def Deserialize(self, s: str) -> TreeNode:
if s == '#':
return None
val_list = s.split(',')
q = queue.Queue()
root = TreeNode(int(val_list[0]))
q.put(root)
for i in range(1, len(val_list), 2):
temp = q.get()
left_val = val_list[i]
right_val = val_list[i + 1]
temp.left = TreeNode(int(left_val)) if left_val != '#' else None
temp.right = TreeNode(int(right_val)) if right_val != '#' else None
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
return root