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];
    }
};
相关推荐
艾莉丝努力练剑2 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
珊瑚里的鱼7 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
凌肖战12 小时前
力扣网编程135题:分发糖果(贪心算法)
算法·leetcode
Norvyn_713 小时前
LeetCode|Day11|557. 反转字符串中的单词 III|Python刷题笔记
笔记·python·leetcode
chao_78914 小时前
动态规划题解_零钱兑换【LeetCode】
python·算法·leetcode·动态规划
吃着火锅x唱着歌14 小时前
LeetCode 424.替换后的最长重复字符
linux·算法·leetcode
Maybyy14 小时前
力扣454.四数相加Ⅱ
java·算法·leetcode
逐闲18 小时前
LeetCode热题100【第一天】
算法·leetcode
爱吃涮毛肚的肥肥(暂时吃不了版)18 小时前
剑指offer——模拟:顺时针打印矩阵
算法·leetcode·矩阵
chao_78918 小时前
动态规划题解——乘积最大子数组【LeetCode】
python·算法·leetcode·动态规划