题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
思路
二叉树的序列化就是按照某种顺序遍历二叉树,遇到空结点是在遍历输出序列中 加入某个特殊字符进行标识,反序列化就是按照同样的规则将一个序列还原为一颗二叉树。 这里采用前序遍历的顺序进行序列化
代码语言:javascript复制# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
valuelist = []
self.preorder(root, valuelist)
# 将结点值序列转化为一个字符串
return ','.join(map(str, valuelist))
def preorder(self, root, valuelist):
if not root:
# 对于空结点,返回#字符加以标识
valuelist.append('#')
return None
valuelist.append(root.val)
self.preorder(root.left, valuelist)
self.preorder(root.right, valuelist)
# write code here
def Deserialize(self, s):
valuelist = s.split(',')
root = self.preorderdes(valuelist)
return root
def preorderdes(self, valuelist):
if len(valuelist) == 0 or valuelist[0] == '':
return None
# 遇到#字符,直接删除,返回空结点
if valuelist[0] == '#':
del valuelist[0]
return None
root = TreeNode(int(valuelist[0]))
del valuelist[0]
root.left = self.preorderdes(valuelist)
root.right = self.preorderdes(valuelist)
return root