LeetCode刷题实战449:序列化和反序列化二叉搜索树
共 3016字,需浏览 7分钟
· 2021-11-26
Serialization is 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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
示例
示例 1:
输入:root = [2,1,3]
输出:[2,1,3]
示例 2:
输入:root = []
输出:[]
解题
/**
* 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 "#";
}
return to_string(root -> val) + ' ' + serialize(root -> left) + ' ' + serialize(root -> right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
stringstream ss(data);
return decode(ss);
}
TreeNode* decode(stringstream &ss) {
string data;
ss >> data;
if(data == "#") {
return NULL;
}
TreeNode* root = new TreeNode(stoi(data)); // stringstream读到的第一段字符串是根节点的值
root -> left = decode(ss); // 递归调用decode()方法对左右子树建树,并将root与左右子树连接起来
root -> right = decode(ss);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
LeetCode刷题实战446:等差数列划分 II - 子序列