简化版前序遍历,序列化过程中将空结点记为’n’,每个结点用空格隔开
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res = dfs_s(root);
return res;
}
string dfs_s(TreeNode* root)
{
if(!root) return "n ";
return to_string(root -> val) + ' ' + dfs_s(root -> left) + dfs_s(root -> right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
auto res = dfs_d(data);
return res;
}
TreeNode* dfs_d(string& s)
{
if(s[0] == 'n') //若以n开头,返回空结点,删掉开头的n和一个空格
{
s = s.substr(2);
return NULL;
}
int val = 0, k = 0, fu = 0;
if(s[0] == '-') k++, fu = 1; // 如果是负数则,k后移一位,并记下符号位
while(s[k] != ' ') val = val * 10 + s[k++] - '0' ;
if(fu) val *= -1;
s = s.substr(k + 1); // 将该数删掉
auto root = new TreeNode(val);
root -> left = dfs_d(s);
root -> right = dfs_d(s);
return root;
}
};