istringstream和ostringstream
从istringstream类中读取数据赋值给某个string,写入某个string到ostringstream类,头文件<sstream>
实例:leetcode297
297. Serialize and Deserialize Binary Tree 序列化和反序列化二叉树
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file
or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer
environment.
Design an algorithm to serialize and deserialize a binary tree.There is no restriction on how your serialization / deserialization
algorithm should work.You just need to ensure that a binary tree can be serialized to a string and this string can be
deserialized to the original tree structure.
Example:
You may serialize the following tree :
1
/
2 3
/
4 5
as "[1,2,3,null,null,4,5]"
Clarification: The above format is the same as how LeetCode serializes a binary tree.You do not necessarily need to follow
this format, so please be creative and come up with different approaches yourself.
Note : Do not use class member / global / static variables to store states.Your serialize and deserialize algorithms should be
stateless.
将一个二叉树的值转化为一个string输出,同时又能把这种string转化二叉树;
前序、中序、后序、层序遍历均可;
法一:
非递归层序遍历以及由层序遍历来构造二叉树;
主要要使用string流,不用string流的话,对于像"[11,-2,3,null,null,42,5]"这样val值大于9或者val值为负数的,你不好处理;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if (root == NULL) return "#"; ostringstream out; queue<TreeNode*> que; que.push(root); while (!que.empty()) { TreeNode* cur = que.front(); que.pop(); if (cur) { out << to_string(cur->val) << " ";//向ostringstream类out中写入,记住要写空格字符串“ ” que.push(cur->left); que.push(cur->right); } else out << "# ";//记住要写空格字符串“ ” } return out.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data == "#") return NULL; istringstream in(data); queue<TreeNode*> que; string valString; in >> valString;//从istringstream类in中读取一个string赋值给valString,istringstream类默认以空格为分隔符 TreeNode* root = new TreeNode(stoi(valString)); que.push(root); while (!que.empty()) { TreeNode* cur = que.front(); que.pop(); in >> valString; if (valString == "") break; if (valString != "#") { cur->left = new TreeNode(stoi(valString)); que.push(cur->left); } in >> valString; if (valString == "") break; if (valString != "#") { cur->right = new TreeNode(atoi(valString.c_str())); que.push(cur->right); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));