序列化格式:
8
/ \
12 2
/ \
6 4
"8 12 2 null null 6 4 null null null null"
BFS实现 - 层级遍历:
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) {
return "null";
}
// bfs
ostringstream oss;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
TreeNode* p = que.front();
que.pop();
if (p) {
oss << p->val << " ";
que.push(p->left);
que.push(p->right);
} else {
oss << "null" << " ";
}
}
return oss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream iss(data);
string s;
iss >> s;
if (s == "null")
return NULL;
// init root
TreeNode *root = new TreeNode(atoi(s.c_str()));
queue<TreeNode*> que;
que.push(root);
// bfs
while (!que.empty()) {
TreeNode* p = que.front();
que.pop();
string l, r;
iss >> l >> r;
if (l != "null") {
p->left = new TreeNode(atoi(l.c_str()));
que.push(p->left);
}
if (r != "null") {
p->right = new TreeNode(atoi(r.c_str()));
que.push(p->right);
}
}
return root;
}
};