/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classCodec { public:
// Encodes a tree to a single string. string serialize(TreeNode* root){ if (!root) returnstring(); stringstream ss; queue<TreeNode*> q; q.push(root); while (!q.empty()) { auto t = q.front(); q.pop(); if (!t) ss << "# "; else { ss << to_string(t -> val) << " " ; q.push(t -> left); q.push(t -> right); } } return ss.str(); }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ if (data.empty()) returnNULL; stringstream ss(data);//将字符串data复制到ss中 string t; ss >> t;//相当于把ss的每个字符一个个输入t中 queue<TreeNode*> q; auto root = newTreeNode(stoi(t)); q.push(root); while (q.size()) { auto p = q.front(); q.pop(); //创建左子树 ss >> t; //读入字符串中除空格的每个字符 if (t == "#") p ->left = NULL; else { p -> left = newTreeNode(stoi(t)); q.push(p -> left); } //创建右子树 ss >> t; if (t == "#") p -> right = NULL; else{ p -> right = newTreeNode(stoi(t)); q.push(p -> right); } } return root; } };
// Your Codec object will be instantiated and called as such: // Codec ser, deser; // TreeNode* ans = deser.deserialize(ser.serialize(root));