1 #include <iostream> 2 #include<vector> 3 #include <stack> 4 #include<map> 5 #include<list> 6 #include <sstream> 7 #include <algorithm>//里边有好多现成的函数 8 #include <queue> 9 10 using namespace std; 11 12 struct TreeNode { 13 int val; 14 struct TreeNode *left; 15 struct TreeNode *right; 16 TreeNode(int x) : 17 val(x), left(NULL), right(NULL) { 18 } 19 }; 20 struct ListNode { 21 int val; 22 struct ListNode *next; 23 ListNode(int x) : 24 val(x), next(NULL) { 25 } 26 }; 27 struct RandomListNode { 28 int label; 29 struct RandomListNode *next, *random; 30 RandomListNode(int x) : 31 label(x), next(NULL), random(NULL) { 32 } 33 }; 34 struct TreeLinkNode { 35 int val; 36 struct TreeLinkNode *left; 37 struct TreeLinkNode *right; 38 struct TreeLinkNode *next; 39 TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) { 40 } 41 }; 42 class Solution { 43 public: 44 /*请实现两个函数,分别用来序列化和反序列化二叉树*/ 45 TreeNode* decode(char *&str) { 46 if (*str == '#'){ 47 str++; 48 return NULL; 49 } 50 int num = 0; 51 while (*str != ',') 52 num = num * 10 + (*(str++) - '0'); 53 str++; 54 TreeNode *root = new TreeNode(num); 55 root->left = decode(str); 56 root->right = decode(str); 57 return root; 58 } 59 char* Serialize2(TreeNode *root) { 60 if (!root) return "#"; 61 string r = to_string(root->val); 62 r.push_back(','); 63 char *left = Serialize(root->left); 64 char *right = Serialize(root->right); 65 char *ret = new char[strlen(left) + strlen(right) + r.size()]; 66 strcpy_s(ret, sizeof(r.c_str()),r.c_str()); 67 strcat(ret, left); 68 strcat(ret, right); 69 return ret; 70 } 71 TreeNode* Deserialize2(char *str) { 72 return decode(str); 73 } 74 75 char* Serialize(TreeNode *root) 76 { 77 //先序遍历 中序遍历 保存结果 78 if (root == NULL) return NULL; 79 vector<TreeNode*>preOrder, inOrder; 80 PreOrder(root, preOrder); 81 InOrderTraverse(root, inOrder); 82 83 char * combine = new char[preOrder.size()+inOrder.size()+1]; 84 for (int i = 0; i < preOrder.size();i++) 85 { 86 combine[i] = preOrder[i]->val; 87 } 88 for (int i = preOrder.size(); i < preOrder.size() + inOrder.size(); i++) 89 { 90 combine[i] = inOrder[i - preOrder.size()]->val; 91 } 92 combine[preOrder.size() + inOrder.size()] = '