leecode第二百九十七题(二叉树的序列化与反序列化)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) {//结果并不是层序 if (root == NULL) return "#_"; string res = to_string(root->val) + "_"; res += serialize(root->left); res += serialize(root->right); return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) {//先打入一个队列里 stringstream ss(data); string item; queue<string> q; while (getline(ss, item, '_')) q.push(item); return helper(q); } TreeNode* helper(queue<string>& q)//对队列进行反序列化 { string val = q.front(); q.pop(); if (val == "#") return NULL; TreeNode* head = new TreeNode(stoi(val)); head->left = helper(q); head->right = helper(q); return head; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
分析:
层序遍历。