面试题37:序列化二叉树
题目:请实现两个函数,分别用来序列化和反序列化二叉树。
#include<iostream>
using namespace std;
struct BinaryTreeNode {
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
// 序列化
void Serialize(BinaryTreeNode* pRoot, ostream& stream){
if(pRoot==NULL){
stream<<"$,";
return;
}
stream<<pRoot->value<<",";
Serialize(pRoot->left, stream);
Serialize(pRoot->right, stream);
}
// 反序列化
void Deserialize(BinaryTreeNode** pRoot, istream& stream){
int number;
if(ReadStream(stream, &number)){
*pRoot=new BinaryTreeNode();
(*pRoot)->value=number;
(*pRoot)->left=NULL;
(*pRoot)->right=NULL;
Deserialize(&((*pRoot)->left), stream);
Deserialize(&((*pRoot)->right), stream);
}
}
int main() {
return 0;
}
愿你慢慢变强
发布了40 篇原创文章 · 获赞 41 · 访问量 923
私信
关注