【剑指Offer-37】序列化二叉树
问题
请实现两个函数,分别用来序列化和反序列化二叉树。
示例
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
解答1:迭代(层序遍历)
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
queue<TreeNode*> q;
string res;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
if (!cur) res += 'x'; // x代表NULL
else {
res += to_string(cur->val);
q.push(cur->left);
q.push(cur->right);
}
res += ' '; // 空格为分隔符
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<TreeNode*> nodes;
string s;
istringstream is(data);
while (is >> s) {
if (s == "x") nodes.push_back(NULL);
else nodes.push_back(new TreeNode(stoi(s)));
}
int pos = 1;
for (int i = 0; i < nodes.size(); i++) {
if (!nodes[i]) continue;
nodes[i]->left = nodes[pos++];
nodes[i]->right = nodes[pos++];
}
return nodes[0];
}
};
重点思路
层序遍历,编码时使用空格分隔是为了后续使用istringstream
,该方法可以在while
中使用>>
将每个值传入string
中。
解答2:递归(前序遍历)
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "x";
return to_string(root->val) + " " + serialize(root->left) + " " + serialize(root->right) + " ";
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream is(data);
return recur(is);
}
private:
TreeNode* recur(istringstream& is) {
string s;
is >> s;
if (s == "x") return NULL;
TreeNode* node = new TreeNode(stoi(s));
node->left = recur(is);
node->right = recur(is);
return node;
}
};
重点思路
要简单递归只能采用前序遍历。这道题得出的结论就是,涉及到字符串编解码问题的时候istringstream
真好用。