题目链接
描述
思路:
自行序列化和反序列化。元素用逗号分隔。
序列化: 使用队列+层序遍历。遍历每一层节点,并访问其左右孩子,如果是空则序列化成#,如果是数字,则序列化成str。
反序列化: 使用队列+两两遍历字符串,按层次构造二叉树。具体做法是:先将根节点入队。然后遍历队列,每取出一个节点,就取两个字符,作为其左右孩子。如果字符为#,说明孩子为空,如果字符为数字,说明孩子不为空,并将其压进队列。(讲的有点难懂。。)
python">import queue
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:def Serialize(self, root):# write code hereresult = ""if root is None:return resultq = queue.Queue()q.put(root)result += str(root.val) + ","while not q.empty():node = q.get()if node.left:q.put(node.left)result += str(node.left.val) + ","else:result += "#,"if node.right:q.put(node.right)result += str(node.right.val) + ","else:result += "#,"return resultdef Deserialize(self, s):if s == "":return Nones = s.split(",")# 数字压进队列,get一个数字就赋值左右孩子q = queue.Queue()root = TreeNode(int(s[0]))q.put(root)cur = 1while not q.empty() and cur < len(s):node = q.get()# 处理左节点val = s[cur]print(val, cur)if val == "#":node.left = Noneelse:new_node = TreeNode(int(val))node.left = new_nodeq.put(new_node)cur += 1# 处理右节点val = s[cur]if val == "#":node.right = Noneelse:new_node = TreeNode(int(val))node.right = new_nodeq.put(new_node)cur += 1return root
来还债了