1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Codec 11 { 12 public: 13 // Encodes a tree to a single string. 14 string serialize(TreeNode* root) 15 { 16 if (root == NULL) 17 return "#_"; 18 string res = to_string(root->val) + "_"; 19 res += serialize(root->left); 20 res += serialize(root->right); 21 return res; 22 } 23 24 // Decodes your encoded data to tree. 25 TreeNode* deserialize(string data) //"1_2_3_#_#_4_5_"切分成为[1,2,3,#,#,4,5] 26 { 27 stringstream ss(data); 28 string item; 29 queue<string> q; 30 while (getline(ss, item, ‘_‘)) q.push(item); 31 return helper(q); 32 } 33 TreeNode* helper(queue<string>& q) 34 { 35 string val = q.front(); 36 q.pop(); 37 if (val == "#") return NULL; 38 TreeNode* head = new TreeNode(stoi(val)); 39 head->left = helper(q); 40 head->right = helper(q); 41 return head; 42 } 43 };
原文:https://www.cnblogs.com/yuhong1103/p/12555055.html