具体思想:
第三次见了,这道题目,二叉树序列化和建树的经典题目;
具体代码:
/**
* 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){
return "null";
}
return to_string(root->val)+" "+serialize(root->left)+" "+serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* root=nullptr;
istringstream ss(data);
root=dfs(ss);
return root;
}
TreeNode* dfs(istringstream& ss){
string temp;
ss>>temp;
if(temp=="null"){
return nullptr;
}
TreeNode* root=new TreeNode(stoi(temp.c_str()));
root->left=dfs(ss);
root->right=dfs(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;```