Title Description:
Implement two functions, respectively, to serialize and deserialize a binary tree.
Analysis: For serialization: Using a pre-order traversal, recursively converts the value of a two-fork tree to a character, and adds a ', ' as a division after the converted Val-derived character after each binary tree node is not empty. For empty nodes, replace with ' # '.
char* Serialize (TreeNode *root) {
if (root = null)
return null;
String str;
Serialize (root, str);
Char *ret = new Char[str.length () +1];
int i;
for (i = 0; i < str.length (); i++) {
ret[i] = Str[i];
}
Ret[i] = ' + ';
return ret;
}
void Serialize (treenode* root, string& str) {
if (root = NULL) {
str + = ' # ';
return;
}
String r = to_string (root->val);
str + = r;
str + = ', ';
Serialize (Root->left, str);
Serialize (Root->right, str);
}
For deserialization: A binary tree is created recursively using the characters in the string in the order of precedence (note: In recursion, the parameters of the recursive function must be char * *, so that the pointer to the string after each recursion is moved with recursion ...) )
treenode* deserialize (char *str) {if (str = = NULL) return null;
TreeNode *ret = Deserialize (&STR);
return ret;
} treenode* Deserialize (char **str) {if (**str = = ' #) {+ + (*STR);
return NULL:} int num = 0;
while (**str! = ' \ ' && **str! = ', ') {//To join **STR if it is ' \ n ' judgment, otherwise the array will be out of memory of num = num*10 + ((**str)-' 0 ');
+ + (*STR);
} TreeNode *root = new TreeNode (num);
if (**str = = ' + ')//indicates that the string has been processed and returned directly to root; Else (*STR) + +;
Otherwise, the pointer moves backwards, continuing the recursive processing of the left and right subtree Root->left = deserialize (str);
Root->right = Deserialize (str);
return root; }