c_cpp 二叉树的序列化和反序列化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 二叉树的序列化和反序列化相关的知识,希望对你有一定的参考价值。
// Compile by: $ g++ test.cpp --std=c++11
#include "BinaryTreeUtils.h"
#include <iostream> // std::cout, std::endl
// #include <string> // std::string
void preorder(BinaryTreeUtils::Node* aNode)
{
if (!aNode) {
std::cout << nullStr << std::endl;
return;
}
std::cout << aNode->data << std::endl;
preorder(aNode->left);
preorder(aNode->right);
}
int main()
{
// Binary Tree:
//
// 30
// / \
// / \
// / \
// / \
// 10 20
// / \ / \
// / \ / \
// / \ / \
// 50 # 45 35
// / \ / \ / \
// # # # # # #
//
// Pre-order : 30 10 50 # # # 20 45 # # 35 # #
// In-order : # 50 # 10 # 30 # 45 # 20 # 35 #
// Post-order : # # 50 # 10 # # 45 # # 35 20 30
BinaryTreeUtils::Node n50 = { 50, nullptr, nullptr };
BinaryTreeUtils::Node n10 = { 10, &n50, nullptr };
BinaryTreeUtils::Node n45 = { 45, nullptr, nullptr };
BinaryTreeUtils::Node n35 = { 35, nullptr, nullptr };
BinaryTreeUtils::Node n20 = { 20, &n45, &n35 };
BinaryTreeUtils::Node n30 = { 30, &n10, &n20 };
std::string DNA = BinaryTreeUtils::Serialize(&n30);
std::cout << DNA << std::endl;
BinaryTreeUtils::Node* tree = BinaryTreeUtils::Deserialize(DNA);
preorder(tree);
return 0;
}
#ifndef BINARY_TREE_UTILS
#define BINARY_TREE_UTILS
#include <algorithm> // std::remove_if
#include <cstdlib> // std::calloc
#include <string> // std::string, std::stoi
#include <sstream> // std::istringstream
std::string nullStr = "#";
class BinaryTreeUtils
{
public:
struct Node {
int data;
struct Node* left;
struct Node* right;
};
static std::string Serialize(Node* aRoot)
{
std::string DNA;
Serializer(aRoot, DNA);
// Remove the space at the beginning
const std::size_t start = DNA.find_first_not_of(' ');
return DNA.substr(start);
}
static Node* Deserialize(std::string& aDNA)
{
std::istringstream stream(aDNA);
return Deserializer(stream);
}
private:
static void Serializer(Node* aRoot, std::string& aDNA)
{
if (!aRoot) {
aDNA += " ";
aDNA += nullStr;
return;
}
aDNA += " ";
aDNA += std::to_string(aRoot->data);
Serializer(aRoot->left, aDNA);
Serializer(aRoot->right, aDNA);
}
static Node* Deserializer(std::istringstream& aStream)
{
std::string str;
// Return null if the string is ended or it's null leaf.
if (!(aStream >> str) || !str.compare(nullStr)) {
return nullptr;
}
Node* n = reinterpret_cast<Node*>(calloc(1, sizeof(Node)));
n->data = std::stoi(str);
n->left = Deserializer(aStream);
n->right = Deserializer(aStream);
return n;
}
};
#endif // BINARY_TREE_UTILS
以上是关于c_cpp 二叉树的序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章