活跃农民
- 积分
- 918
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-9-8
- 最后登录
- 1970-1-1
|
楼主,求问N叉树的序列化和反序列化当时用了什么方法?我只想到按层遍历,下面是我的代码,初步测试没有问题,希望楼主给出建议~
- #include <iostream>
- #include <sstream>
- #include <vector>
- #include <queue>
- using namespace std;
- struct TreeNode
- {
- int val;
- vector<TreeNode *> children;
- TreeNode(int v):val(v){}
- };
- string serial(TreeNode* root)
- {
- ostringstream os;
- if(!root) {return "";}
- os<<to_string(root->val)+" ";
- int cnt = root->children.size();
- os<<to_string(cnt)+" ";
- queue<TreeNode* > Q;
- Q.push(root);
- while(!Q.empty()) {
- TreeNode *cur = Q.front();
- Q.pop();
- for(auto child : cur->children) {
- os<<to_string(child->val)+" ";
- int cnt = child->children.size();
- os<<to_string(cnt)+" ";
- Q.push(child);
- }
- }
- return os.str();
- }
- TreeNode* deserial(string s) {
- istringstream ist(s);
- if(ist.eof()) return NULL;
- TreeNode *root = new TreeNode(0);
- queue<TreeNode *> Q;
- Q.push(root);
- while(!Q.empty()) {
- TreeNode *cur = Q.front();
- Q.pop();
- string str;
- ist>>str;
- if (str == "") {
- break;
- }
- cur->val = stoi(str);
- ist>>str;
- if(str == "") break;
- int cnt = stoi(str);
- for(int i = 0; i < cnt; ++i) {
- TreeNode *child = new TreeNode(0);
- cur->children.push_back(child);
- Q.push(child);
- }
- }
- return root;
- }
- int main(int argc, const char * argv[]) {
- string s = "1 3 2 3 3 0 4 0 5 0 6 0 7 0";
- TreeNode *root = deserial(s);
- cout<<serial(root)<<endl;
- }
复制代码 |
|