详见:https://leetcode.com/problems/serialize-and-deserialize-bst/description/
C++:
/** * 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) { ostringstream os; serializeHelper(root,os); return os.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream is(data); return deserializeHelper(is); } void serializeHelper(TreeNode* root,ostringstream &os) { if(!root) { os<<"# "; } else { os<<root->val<<" "; serializeHelper(root->left,os); serializeHelper(root->right,os); } } TreeNode* deserializeHelper(istringstream &is) { string val; is>>val; if(val=="#") { return nullptr; } TreeNode* node=new TreeNode(stoi(val)); node->left=deserializeHelper(is); node->right=deserializeHelper(is); return node; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
参考:https://www.cnblogs.com/grandyang/p/6224510.html