LeetCode刷题_c++版-449 序列化和反序列化二叉搜索树

/**
 * 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:
    //先根序遍历二叉树,插入字符串,若数字为54,插入后变为“45#”
    void preOrder(TreeNode* root, string& result){
    
    
        if(root) {
    
    
            int num = root->val;
            while(num != 0){
    
    
                //从低位到高位逆序插入字符串
                result.push_back(num%10 +'0');
                num = num/10;
            }
            result += '#';
            preOrder(root->left, result);
            preOrder(root->right, result);
        }
        
    }
    // Encodes a tree to a single string.

    string serialize(TreeNode* root) {
    
    
        string result = "";
        preOrder(root, result);
        return result;
        
    }


    void insertNode(TreeNode* &root, int num){
    
    
        //根为空,则创建新节点插入
        if(root == NULL) {
    
    
            //cout<< "insert";
            root = new TreeNode(num);
            return;
        }
        //大于根,则插入根的右子树
        else if(num >= root->val){
    
    
            //cout<< "num = "<< num<< " root="<<root->val<< " right"<<endl;
            insertNode(root->right, num);
        }
        //小于根,则插入根的左子树
        else {
    
    
            //cout<< "num = "<< num<< " root="<<root->val<< " left"<<endl;
            insertNode(root->left, num);
        }
    }
    // Decodes your encoded data to tree.

    TreeNode* deserialize(string data) {
    
    
        TreeNode* root = NULL;
        //cout << data <<"  length="<<data.length()<< endl;
        if(data.length() == 0) return root;
        //count标记位数
        int count = 0;
        for(int i = 0; i< data.length(); i++ ){
    
    
            int sum = 0;
            //没遇到“#”则认为还是同一个数
            while(data[i] != '#'){
    
    
                int num = data[i]-'0';
                //cout<< "data="<<data[i]<<" num="<< num<<" count="<<count<<endl;
                for(int j = 0; j < count;j++){
    
    
                    //cout<< num<< endl;
                    //高位需乘10
                    num = num * 10;
                }
                
                count += 1;
                sum +=  num;
                i++;
            }
            //cout<<"push "<< sum<< endl;
            count = 0;
            insertNode(root, sum);
        }return root;
        
    }
};

// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44343355/article/details/129098831
今日推荐