Implements two functions for serializing and deserializing binary trees.
Serialize a binary tree. Given a binary tree, traverse it in some way. The empty child node is represented by '#', and the numbers are separated by commas.
such as
The results of serialization are: 1, 2, 4, 3, 5, 6##
In the process of serialization, the preorder traversal method of binary tree can be considered for serialization.
//Convert int data to str string to_string(int val) { string res=""; while(val) { int num=val%10; char temp=num+48; res+=temp; val/=10; } reverse(res.begin(),res.end()); return res; } string str=""; //Serialize main function void S_core(TreeNode *root,string &str) { if(root==NULL) { str+='#'; return; } else { str+=to_string(root->val); str+=','; S_core(root->left,str); S_core(root->right,str); } } //Serialization function char* Serialize(TreeNode *root) { if(root==NULL) return NULL; S_core(root,str); char *s=new char[str.size()+1]; for(int i=0;i<str.size();i++) { s[i]=str[i]; } s[str.size()]='\0'; return s; }
The deserialization corresponding to serialization also adopts the way of preorder traversal.
Note that the parameter of the d'u core function is a reference, which can also be used as a secondary pointer.
//Deserialize main function TreeNode* D_core(char* &str) { if(*str=='#') { str++; return NULL; } int num=0; while(*str!=','&&*str!='\0') { num=num*10+*str-'0'; str++; } TreeNode *root=new TreeNode(num); if(*str=='\0') return root; else str++; root->left=D_core(str); root->right=D_core(str); return root; } //Deserialization function TreeNode* Deserialize(char *str) { if(str==NULL) return NULL; else return D_core(str); }