题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
题解:
注意string 到 char*的转换
1 class Solution { 2 public: 3 char* Serialize(TreeNode *root) { 4 string str = ""; 5 preOrder(root, str); 6 char *c = new char[str.size() + 1]; 7 strcpy(c, str.c_str()); 8 return c; 9 } 10 void preOrder(TreeNode *root, string &str) 11 { 12 if (root == nullptr) 13 { 14 str += "#"; 15 return; 16 } 17 str += to_string(root->val) + "!"; 18 preOrder(root->left, str); 19 preOrder(root->right, str); 20 } 21 TreeNode* Deserialize(char *str) { 22 string s = str; 23 int index = 0; 24 return createTree(s, index); 25 } 26 TreeNode* createTree(const string &str, int &index) 27 { 28 TreeNode* root = nullptr; 29 if (str[index] == '#' || index == str.size()) 30 { 31 index++; 32 return root; 33 } 34 string s = ""; 35 while (str[index] != '!') 36 s += str[index++]; 37 index++; 38 root = new TreeNode(atoi(s.c_str())); 39 root->left = createTree(str, index); 40 root->right = createTree(str, index); 41 return root; 42 } 43 };