详细思路在注释里
1. 通过序列化,可以只使用先序遍历就可以唯一确定一颗二叉树。
2. 序列化时:空节点用"#,"表示,非空节点用其节点的val值加逗号表示。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
// 将二叉树序列化
string res;// 用于存储序列化后的二叉树
dfs1(root, res);
return res;
}
// res需要传入引用
void dfs1(TreeNode* root, string& res){
// 当节点为空,向res中存入"#,"
if (!root){
res += "#,";
return;
}
// 向res中存入该节点的val和逗号
res += to_string(root->val) + ',';
dfs1(root->left, res);
dfs1(root->right, res);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
// u用来记录反序列化到了二叉树的第几个节点
int u = 0;
return dfs2(data, u);
}
TreeNode* dfs2(string& data, int& u){
// 若当前元素为'#',则说明遍历到了一个空节点,u加2,向后移动两个位置
if (data[u] == '#'){
u += 2;
return NULL;
}
int t = 0;
bool is_minus = false;// 用于标记data中记录的节点对应的val值的正负
// 当遇到负号 is_minus变为true,且u再向后移动一个位置
if (data[u] == '-'){
is_minus = true;
u++;
}
// 向后遍历,直到碰到逗号为止,获取当前节点的val
while (data[u] != ','){
// val可能为1位数,两位数,三位数.....
t = t * 10 + data[u] - '0';
u++;// 向后移动一位
}
u++;
// 若is_minus为true,需要给t乘上负一
if (is_minus){
t = -t;
}
// 根据获取到的val值t,创建一个二叉树节点
auto root = new TreeNode(t);
// 再获取左子树和右子树
root->left = dfs2(data, u);
root->right = dfs2(data, u);
return root;
}
};