60序列化二叉树
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树。
思路:序列化就是将一个数据结构或物体转化为一个位序列,可以存进一个文件或者内存缓冲器中,然后通过网络连接在相同的或者另一个电脑环境中被还原,还原的过程叫做去序列化。
使用C++ ostringstream来格式化字符串输出,使用一次后清空的话使用
ostringstream os; os << "1234" << " "; string s = os.str();//获得输出流的数据 char* p; strcpy(p,s.c_str());//获得c风格字符串格式 os.str("");//清空
string不能直接赋值给char*。
s.c_str()是一个const char*形式,不能赋值给char*,必须通过strcpy()。
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: void helper_ser(TreeNode *root,ostringstream &os){ if(root == nullptr){ os << "#" << " "; return; } os << to_string(root->val) << " "; helper_ser(root->left,os); helper_ser(root->right,os); } TreeNode* helper_des(istringstream &in){ string tmp; in >> tmp; TreeNode* root; if(tmp == "#"){ root = nullptr; return root; } root = new TreeNode(stoi(tmp)); root->left = helper_des(in); root->right = helper_des(in); return root; } char resStr[1000000]; char* Serialize(TreeNode *root) { if(root == nullptr){ resStr[0] = '#'; resStr[1] = '\0'; return resStr; } ostringstream os; helper_ser(root,os); strcpy(resStr,os.str().c_str()); return resStr; } TreeNode* Deserialize(char *str) { istringstream in(str); TreeNode* root; root = helper_des(in); return root; } };
循环版本:
使用层次遍历,queue的思想。
// Non-recursion class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { ostringstream out; queue<TreeNode*> q; if (root) q.push(root); while (!q.empty()) { TreeNode *t = q.front(); q.pop(); if (t) { out << t->val << ' '; q.push(t->left); q.push(t->right); } else { out << "# "; } } return out.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.empty()) return nullptr; istringstream in(data); queue<TreeNode*> q; string val; in >> val; TreeNode *res = new TreeNode(stoi(val)), *cur = res; q.push(cur); while (!q.empty()) { TreeNode *t = q.front(); q.pop(); if (!(in >> val)) break; if (val != "#") { cur = new TreeNode(stoi(val)); q.push(cur); t->left = cur; } if (!(in >> val)) break; if (val != "#") { cur = new TreeNode(stoi(val)); q.push(cur); t->right = cur; } } return res; } };