剑指 Offer 37-序列化二叉树C++

还债第二题

题目描述

在这里插入图片描述

解法 BFS

BFS就不多说了,这题难点个人觉得是string和int之间的处理。
先放一个看到字符总结的博文C,C++字符串总结
这是第二次碰到ostringstream / istringstream ,是非常好用的两个输入流,ostringstream的str()函数可以将以空格隔开的一系列数字转为以逗号隔开的字符串
**这题里面istringstream的用法还是和leetcode-58遇到的一样:将大的字符串里面以逗号隔开的每个字符串作为新的字符串来处理
大概格式就是这样

 		istringstream in(data);
        string tmp;
        while(in >> tmp) {
    
    
        //do something
        }

还看到了stoi函数:可以把字符串转为数字。越过int上限会报错
关于stoi和atoi
关于c++更详细的知识点会在这个寒假逐一攻破,毕竟面试也不只是写个函数。战斗远远不止算法

/**
 * 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) {
    
    
        ostringstream out;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
    
    
            TreeNode* tmp = q.front();
            q.pop();
            if(tmp != NULL) {
    
    
                out<<tmp -> val<<" ";
                q.push(tmp -> left);
                q.push(tmp -> right);
            }
            else out<<"null ";
        }
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
    
    
        istringstream in(data);
        string tmp;
        vector<TreeNode*> a;
        while(in >> tmp) {
    
    
            if(tmp =="null") {
    
    
                a.push_back(NULL);
            }
            //stoi 把字符串转为int
            else a.push_back(new TreeNode(stoi(tmp)));
        }
        int index = 1;
        for(int i = 0; index < a.size(); i ++) {
    
    
            if(a[i] == NULL) continue;
            if(index < a.size()) a[i] -> left = a[index ++];
            if(index < a.size()) a[i] -> right= a[index ++];
        }
        return a[0];
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

在这里插入图片描述
时间复杂度 不知道ostringstream和istringstream是多少… 留个坑
空间复杂度

猜你喜欢

转载自blog.csdn.net/qq_42883222/article/details/112984375