微光拼图 发表于 2022-10-24 16:51:27

二叉树序列化和反序列化的主函数

#include<bits/stdc++.h>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
    public:
    string serialize(TreeNode *root)
    {
      if(!root){
            return "#_";
      }
      return to_string(root->val) + "_" + serialize(root->left) + serialize(root->right);
    }
    TreeNode *deserialize(string data)
    {
      cout << data << endl;
      queue<string> q;
      stringstream ss(data);
      string s;
      while(getline(ss, s, '_'))
      {
            q.push(s);
      }
      return help(q);
    }
    TreeNode *help(queue<string> &q)
    {
      auto cur = q.front();
      q.pop();
      if(cur == "#")
      {
            return NULL;
      }
      auto root = new TreeNode(stoi(cur));//cur转10进制
      root->left = help(q);
      root->right = help(q);
      return root;
    }
};

微光拼图 发表于 2022-10-24 22:07:12

已解决https://cdn.nlark.com/yuque/0/2022/png/22228359/1666620377980-908365c4-4b1b-4132-adc6-372535c714e1.png
页: [1]
查看完整版本: 二叉树序列化和反序列化的主函数