二叉树的序列化与反序列化

定义一个二叉树

#ifndef C__TEST01_NODE_HPP
#define C__TEST01_NODE_HPP
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
using namespace std;

class Node{
public:
    int value;
    Node* left;
    Node* right;
    Node(int value):value(value){
        left = nullptr;
        right = nullptr;
    }
};

算法

//求二叉树序列化和反序列化
//生成两个二叉树
Node* serializeTreeInit(bool x = true){
    if(x){
        Node* head = new Node(1);
        head->right = new Node(1);
        head->right->left = new Node(1);
        return head;
    }else{
        Node* head = new Node(1);
        head->left = new Node(1);
        head->left->right = new Node(1);
        return head;
    }
}

string serializeTree(Node *head){
    if(head == nullptr) {
        return "#_";
    }
    string output = to_string(head->value)+"_";
    string s1 = serializeTree(head->left);
    string s2 = serializeTree(head->right);
    return output + s1 + s2;
}

Node* string_to_tree(queue<char> &q){
    char value = q.front();
    q.pop();
    if(value == '#'){
        return nullptr;
    }
    int v = value - '0';
    Node *head = new Node(v);
    head->left = string_to_tree(q);
    head->right = string_to_tree(q);
    return head;
}
Node* string_to_tree(string serializeString){
    vector<char> splitArr;
    for (int i = 0; i < serializeString.size(); ++i) {
        if(serializeString[i] != '_'){
            splitArr.push_back(serializeString[i]);
        }
    }
    queue<char> q;
    for (int i = 0; i < splitArr.size(); ++i) {
        q.push(splitArr[i]);
    }

    return string_to_tree(q);
}

posted @ 2021-08-03 18:19  蘑菇王国大聪明  阅读(30)  评论(0编辑  收藏  举报