Serialize and Deserialize Binary Tree

本文介绍了一种二叉树的序列化与反序列化的算法实现,使用字符串形式来保存二叉树结构,并能从该字符串重建原始树结构。通过递归方式实现了序列化过程,并利用istringstream辅助完成反序列化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Serialize and Deserialize Binary Tree

Total Accepted: 6782 Total Submissions: 27834 Difficulty: Medium

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5
as  "[1,2,3,null,null,4,5]", just the same as  how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

/**
 * 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 res;
        if(!root){
            res+="#.";
            return res;
        }
        res += to_string(root->val)+".";
        res += serialize(root->left);
        res += serialize(root->right);
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        return _deserialize(data);
    }
private:
    TreeNode* _deserialize(string& data) {
        int potpos = data.find_first_of('.',0);
    
        string num = data.substr(0,potpos);
        data.erase(0,potpos+1);
        
        if(num == "#") {
            return NULL;
        }   
        
        TreeNode* root = new TreeNode(atoi(num.c_str()));
        root->left = _deserialize(data);
        root->right = _deserialize(data);
        
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

 漂亮的代码:

/**
 * 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) {
        ostringstream oss;
        serialize(root,oss);
        return oss.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream iss(data);
        return deserialize(iss);
    }
private:
    void serialize(TreeNode* root,ostringstream& oss) {
        if(!root){
            oss<<"# ";    
            return;
        } 
        oss<< root->val << ' ';
        serialize(root->left,oss);
        serialize(root->right,oss);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(istringstream& iss) {
        string val;
        iss>>val;
        if(val=="#") return NULL;
        TreeNode* root = new TreeNode(stoi(val));
        root->left     = deserialize(iss);
        root->right    = deserialize(iss);
        return root;
    }
};

 

转载于:https://www.cnblogs.com/zengzy/p/5057019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值