[LeetCode|[LeetCode 449] 序列化和反序列化二叉搜索树

449. 序列化和反序列化二叉搜索树 【[LeetCode|[LeetCode 449] 序列化和反序列化二叉搜索树】将二叉搜索树前序化,再按前序可以还原出原来的二叉搜索树。
对于一般的树来说,这个过程不是可逆的,一般的树需要前序和中序一起才能还原出来。

#include #include #include #include using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Codec { public: string int2str(int a) { string str=""; if(a==0)return string("0"); while(a) { char c=a%10+'0'; str=c+str; a/=10; } return str; }int str2int(string str,int &i) { int res=0; while(str[i]!='#') { res*=10; res+=str[i]-'0'; i++; } i++; return res; }void preorder(TreeNode *node,string &str) { if(!node)return; str+=int2str(node->val); str+='#'; if(node->left)preorder(node->left,str); if(node->right)preorder(node->right,str); }void BST_insert(TreeNode *node,TreeNode *insert_node) { if(insert_node->valval) { if(node->left) BST_insert(node->left,insert_node); else node->left=insert_node; } else { if(node->right) BST_insert(node->right,insert_node); else node->right=insert_node; } }// Encodes a tree to a single string. string serialize(TreeNode* root) { string str; preorder(root,str); return str; }// Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(datahttps://www.it610.com/article/=="")return NULL; int i=0; int t=str2int(data,i); TreeNode *root=new TreeNode(t); while(ileft=b1; a1->right=b2; b1->left=c1; b1->right=c2; b2->right=c3; Codec c; string str=c.serialize(a1); TreeNode *res=c.deserialize(str); string tmp; c.preorder(res,tmp); cout<

    推荐阅读