二叉树的层次序列化和反序列化-----stringstream

 1 string serialize(TreeNode* root) {//层序便利,将空的子节点也放入到字符串
 2 ostringstream out;
 3 queue<TreeNode*> q;
 4 q.push(root);
 5 while(q.size()){
 6 auto node = q.front();
 7 q.pop();
 8 if(!node){
 9 out << "null" << " ";
10 continue;
11 }
12 out << to_string(node->val) << " ";
13 q.push(node->left);
14 q.push(node->right);
15 }
16 return out.str();
17 }
18 
19 TreeNode* deserialize(string data){
20 istringstream is(data);
21 string val;
22 vector<TreeNode*> vec;
23 while(is >> val){
24 if(val == "null"){
25 vec.push_back(nullptr);
26 continue;
27 }
28 auto node = new TreeNode(stoi(val));
29 vec.push_back(node);
30 }
31 int i = 0,j = 1;
32 while(j < vec.size()){//根据层序遍历输出的顺序得到
33   if(vec[i]{
34 vec[i]->left = vec[j++];//左子树
35 vec[i]->right = vec[j++];//柚子树
36 }  
37 i++;//根节点
38 }
39 return vec[0];
40 }

 

posted @ 2020-05-30 11:12  糖糖_彭  阅读(270)  评论(0编辑  收藏  举报