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));

运行结果

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

相关推荐
xlp666hub3 分钟前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网1 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
有意义2 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103374 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
不想写代码的星星4 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研