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];
    }
};
相关推荐
前端拿破轮32 分钟前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
无聊的小坏坏2 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
qq_5139704418 小时前
力扣 hot100 Day37
算法·leetcode
不見星空18 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
chao_78921 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
GEEK零零七1 天前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战1 天前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
Y1nhl1 天前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
Swift社区1 天前
Swift 解 LeetCode 320:一行单词有多少种缩写可能?用回溯找全解
开发语言·leetcode·swift
YuTaoShao2 天前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展