?LeetCode刷題實(shí)戰(zhàn)449:序列化和反序列化二叉搜索樹
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) { // 空節(jié)點(diǎn)用"#"表示
???????????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讀到的第一段字符串是根節(jié)點(diǎn)的值
????????root -> left = decode(ss); // 遞歸調(diào)用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;
LeetCode1-440題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)441:排列硬幣
LeetCode刷題實(shí)戰(zhàn)442:數(shù)組中重復(fù)的數(shù)據(jù)
LeetCode刷題實(shí)戰(zhàn)443:壓縮字符串
LeetCode刷題實(shí)戰(zhàn)444:序列重建
LeetCode刷題實(shí)戰(zhàn)445:兩數(shù)相加 II
LeetCode刷題實(shí)戰(zhàn)446:等差數(shù)列劃分 II - 子序列
LeetCode刷題實(shí)戰(zhàn)447:回旋鏢的數(shù)量
LeetCode刷題實(shí)戰(zhàn)448:找到所有數(shù)組中消失的數(shù)字
