方法一:递归,流
/**
* 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 {
private:
void encode(TreeNode* root,ostringstream &ss){
if(!root) //前序遍历
ss<<"# ";
else{
ss<<root->val<<' ';
encode(root->left,ss);
encode(root->right,ss);
}
}
TreeNode* decode(istringstream& ss){
string tmp; //前序生成二叉树
ss>>tmp;
if(tmp=="#")
return NULL;
TreeNode* root=new TreeNode(stoi(tmp));
root->left=decode(ss);
root->right=decode(ss);
return root;
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream ss;
encode(root,ss);
return ss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream ss(data);
return decode(ss);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));