37 序列化与反序列化二叉树
题目
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
C++ 题解
序列化二叉树的过程中,如果遇到空节点,需要以某种符号(这里用#)表示。以下图二叉树为例,序列化二叉树时,需要将空节点也存入字符串中。
// 序列化
void Serialize(const BinaryTreeNode* pRoot, ostream& stream)
{
if (pRoot == nullptr)
{
stream << "#,";
return;
}
stream << pRoot->m_nValue << ',';
Serialize(pRoot->m_pLeft, stream);
Serialize(pRoot->m_pRight, stream);
}
bool ReadStream(istream& stream, int* number)
{
if (stream.eof())
return false;
char buffer[32];
buffer[0] = '\0';
char ch;
stream >> ch;
int i = 0;
while (!stream.eof() && ch != ',')
{
buffer[i++] = ch;
stream >> ch;
}
bool isNumeric = false;
if (i > 0 && buffer[0] != '#')
{
*number = atoi(buffer);
isNumeric = true;
}
return isNumeric;
}
// 反序列化
void Deserialize(BinaryTreeNode** pRoot, istream& stream)
{
int number;
if (ReadStream(stream, &number))
{
*pRoot = new BinaryTreeNode();
(*pRoot)->m_nValue = number;
(*pRoot)->m_pLeft = nullptr;
(*pRoot)->m_pRight = nullptr;
Deserialize(&((*pRoot)->m_pLeft), stream);
Deserialize(&((*pRoot)->m_pRight), stream);
}
}
python 题解
当遇到当前指向的字符为特殊字符”#”或者指针超出了序列的长度,则返回None,指针后移,继续遍历。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
flag=-1
def Serialize(self, root):
# write code here
if not root:
return '#'
return str(root.val)+','+self.Serialize(root.left)+','+self.Serialize(root.right)
def Deserialize(self, s):
# write code here
self.flag+=1
lis=s.split(',')
if self.flag>=len(s):
return None
root=None
if lis[self.flag]!='#':
root=TreeNode(int(lis[self.flag]))
root.left=self.Deserialize(s)
root.right=self.Deserialize(s)
return root