题意理解
给定一个二叉树,将它序列化出一个字符串,再反向生成原来的二叉树
问题分析
设计字符串间隔,外加上叶子节点左右空子树的标志。
其他
之前做出来过,现在又不会了。说明挺难的
链接
/**
* 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) {
string res;
if (!root) return "#";
return to_string(root->val) + ' ' + serialize(root->left) + ' ' + serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//cout << "serialize " << data << endl;
istringstream in(data);
return helper(in);
}
TreeNode* helper(istringstream &in) {
string ch;
in >> ch;
if (ch == "#") {
return NULL;
}
TreeNode* root = new TreeNode(stoi(ch));
root->left = helper(in);
root->right = helper(in);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));