leetcode 297. 二叉树的序列化与反序列化

题目:297. 二叉树的序列化与反序列化 - 力扣(LeetCode)

宽度有限搜索的具象化,没啥难度,注意二叉树中空节点的处理即可。

cpp 复制代码
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if (root == nullptr) {
            return "[]";
        }
        vector<TreeNode*> arr;
        arr.push_back(root);
        int i = 0;
        while (i < arr.size()) {
            TreeNode* t = arr[i];
            i++;
            if (!t) {
                continue;
            }
            arr.push_back(t->left);
            arr.push_back(t->right);
        }
        while (arr.size() && arr[arr.size() - 1] == nullptr) {
            arr.pop_back();
        }
        
        string data = "[";
        for (i = 0; i < arr.size(); i++) {
            if (!arr[i]) {
                data += "null";
            } else {
                data += to_string(arr[i]->val);
            }
            if (i < arr.size() - 1) {
                data += ",";
            } else {
                data += "]";
            }
        }
        return data;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        vector<TreeNode*> arr;
        int i = 1;
        int end = data.length() - 2;
        bool neg;
        int val = 0;
        while (i <= end) {
            if (data[i] == 'n') {
                arr.push_back(nullptr);
                i += 5;
                continue;
            }
            neg = false;
            if (data[i] == '-') {
                neg = true;
                i++;
            }
            val = 0;
            while (i <= end && data[i] != ',') {
                val = val * 10 + data[i] - '0';
                i++;
            }
            if (neg) {
                val = - val;
            }
            TreeNode* t = new TreeNode(val);
            arr.push_back(t);
            i++;
        }
        
        if (arr.empty()) {
            return nullptr;
        }
        
        int pid = 0;
        TreeNode* parent;
        for (int i = 1; i < arr.size(); i++) {
            parent = arr[pid];
            if (i % 2 == 1) {
                parent->left = arr[i];
            } else {
                parent->right = arr[i];
                pid++;
                while (!arr[pid]) {
                    pid++;
                }
            }
        }
        return arr[0];
    }
};
相关推荐
夏鹏今天学习了吗38 分钟前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_7968265243 分钟前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535201 小时前
力扣题目练习 换水问题
python·算法·leetcode
一匹电信狗1 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
·白小白3 小时前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
仰泳的熊猫4 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode
水冗水孚4 小时前
双指针算法在实际开发中的具体应用之代码Review文章字符串的片段分割
算法·leetcode
Qiuner5 小时前
《掰开揉碎讲编程-长篇》重生之哈希表易如放掌
数据结构·算法·leetcode·力扣·哈希算法·哈希·一文读懂
缓风浪起7 小时前
【力扣】2011. 执行操作后的变量值
算法·leetcode·职场和发展
电子_咸鱼12 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先