leetcode_二分查找与二叉排序数_449. 序列化和反序列化二叉搜索树

//编译不过版本
class Codec {
public:

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
    if(!root){
        return NULL;
    }
    std::string data;
    BST_preOrder(root,data);
    return data;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
    if(data.length() == 0){
        return NULL;
    }
    std::vector node_vec;
    int val = 0;
    for(int i = 0;i < data.length();i++){
        if(data[i] == '#'){
            node_vec.push_back(new TreeNode(val));
            val = 0;
        }else{
            //字符串转int方法 多一位就乘10
            val = val * 10 + data[i] - '0';
        }
    }
    for(int i = 1;i < node_vec.size();i++){
        BST_insert(node_vec[0],node_vec[i]);
    }
    return node_vec[0];
}

private:
void int_change_to_string(int val,string &str_val){
std::string str;
while(val){
str = val%10 + ‘0’;
val = val/10;
}
for(int i = str.length() - 1;i >= 0;i–){
//将各个节点的str累计到一个string里边
str_val += str[i];
}
str += ‘#’;
}
//递归编码
void BST_preOrder(TreeNode *node,std::string &data){
if(!node){
return ;
}
std::string str;
int_change_to_string(node -> val,str);
data += str;
BST_preOrder(node ->left,data);
BST_preOrder(node ->right,data);
}
void BST_insert(TreeNode *node ,TreeNode *node_in){
//值比根节点小
if(node_in ->val < node ->val){
//左节点不为空 递归插入左字树
if(node ->left){
BST_insert(node->left,node_in);
//没有左节点 就直接链接左指针
}else{
node -> left = node_in;
}
}else{
if(node -> right){
BST_insert(node->right,node_in);
}else{
node -> right = node_in;
}
}
}
};

//编译通过版本
void BST_insert(TreeNode *node, TreeNode *insert_node){
if (insert_node->val < node->val){
if (node->left){
BST_insert(node->left, insert_node);
}
else{
node->left = insert_node;
}
}
else{
if (node->right){
BST_insert(node->right, insert_node);
}
else{
node->right = insert_node;
}
}
}

void change_int_to_string(int val, std::string &str_val){
std::string tmp;
while(val){
tmp += val % 10 + ‘0’;
val = val / 10;
}
for (int i = tmp.length() - 1; i >= 0; i–){
str_val += tmp[i];
}
str_val += ‘#’;
}

void BST_preorder(TreeNode *node, std::string &data){
if (!node){
return;
}
std::string str_val;
change_int_to_string(node->val, str_val);
data += str_val;
BST_preorder(node->left, data);
BST_preorder(node->right, data);
}

class Codec {
public:
std::string serialize(TreeNode* root) {
std::string data;
BST_preorder(root, data);
return data;
}
TreeNode *deserialize(std::string data) {
if (data.length() == 0){
return NULL;
}
std::vector node_vec;
int val = 0;
for (int i = 0; i < data.length(); i++){
if (data[i] == ‘#’){
node_vec.push_back(new TreeNode(val));
val = 0;
}
else{
val = val * 10 + data[i] - ‘0’;
}
}
for (int i = 1; i < node_vec.size(); i++){
BST_insert(node_vec[0], node_vec[i]);
}
return node_vec[0];
}
};

你可能感兴趣的:(数据结构与算法,leetcode,算法,二叉树,数据结构,c++)