DFS比BFS实现起来更简洁。
序列化格式:
8
/ \
12 2
/ \
6 4
"8 12 null null 2 6 null null 4 null null"
DFS实现 - 先序遍历:
void ser(TreeNode *p, ostringstream &oss) {
if (!p) {
oss << "null ";
return;
}
oss << p->val << " ";
ser(p->left, oss);
ser(p->right, oss);
}
void des(TreeNode **p, istringstream &iss) {
string s;
iss >> s;
if (s == "null")
return;
*p = new TreeNode(atoi(s.c_str()));
des(&((*p)->left), iss);
des(&((*p)->right), iss);
}
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream oss;
ser(root, oss);
return oss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode *root;
istringstream iss(data);
des(&root, iss);
return root;
}
};