原題
LintCode 7. Binary Tree Serialization
Description
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
Notice
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.
Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:
3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.
代碼
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
string serialize(TreeNode * root) {
// write your code here
string res = "";
if (root == NULL) return res;
queue<TreeNode *> q;
int notNullCount = 1;
q.push(root);
while (!q.empty() && notNullCount) {
TreeNode *node = q.front();
q.pop();
if (node == NULL) {
res += "#,";
q.push(NULL);
q.push(NULL);
} else {
notNullCount--;
res += to_string(node->val) + ",";
q.push(node->left);
q.push(node->right);
if (node->left) notNullCount++;
if (node->right) notNullCount++;
}
}
return res;
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
TreeNode * deserialize(string &data) {
// write your code here
vector<string> vals;
vector<TreeNode *> nodes;
stringstream ss(data);
string temp;
while (getline(ss, temp, ',')) {
vals.push_back(temp);
}
for (string val : vals) {
if (val == "#") {
nodes.push_back(NULL);
} else {
TreeNode *node = new TreeNode(stoi(val));
if (!nodes.empty()) {
if (nodes.size() % 2) {
nodes[(nodes.size() - 1) / 2]->left = node;
} else {
nodes[(nodes.size() - 1) / 2]->right = node;
}
}
nodes.push_back(node);
}
}
return nodes.empty() ? NULL : nodes.front();
}
};