Leetcode—297. 二叉树的序列化与反序列化【困难】

2024每日刷题(148)

Leetcode---297. 二叉树的序列化与反序列化

实现代码

cpp 复制代码
/**
 * 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) {
        string ans;

        function<void(TreeNode*)> preorder = [&](TreeNode* root) {
            if(root == nullptr) {
                ans += "null ";
                return;
            }
            
            ans += to_string(root->val) + " ";
            preorder(root->left);
            preorder(root->right);
        };

        preorder(root);
        return ans;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream iss(data);

        queue<string> q;
        for(string s; iss >> s;) {
            q.push(s);
        }

        function<TreeNode*()> preorder = [&]() {
            string node = q.front();
            q.pop();
            if(node == "null") {
                return (TreeNode*)nullptr;
            }

            TreeNode* newNode = new TreeNode(stoi(node));
            newNode->left = preorder();
            newNode->right = preorder();
            return newNode;
        };

        return preorder();
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
louiseailife10 分钟前
企业智能体架构解析:五大类型与落地技术路线
经验分享
TL滕15 分钟前
从0开始学算法——第十二天(KMP算法练习)
笔记·学习·算法
Math_teacher_fan19 分钟前
第二篇:核心几何工具类详解
人工智能·算法
汉克老师20 分钟前
CCF-NOI2025第二试题目与解析(第二题、集合(set))
c++·算法·noi·子集卷积·sos dp·mod 异常
Ayu阿予43 分钟前
C++从源文件到可执行文件的过程
开发语言·c++
福尔摩斯张1 小时前
基于C++的UDP网络通信系统设计与实现
linux·c语言·开发语言·网络·c++·tcp/ip·udp
mit6.8241 小时前
presum|
算法
不穿格子的程序员1 小时前
从零开始写算法——链表篇2:从“回文”到“环形”——链表双指针技巧的深度解析
数据结构·算法·链表·回文链表·环形链表
hkNaruto1 小时前
【规范】Linux平台C/C++程序版本发布调试规范手册 兼容银河麒麟
linux·c语言·c++