[LeetCode 297] Serialize and Deserialize Binary Tree

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.

Example: 

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]"

Clarification: The above format is the same as how LeetCode 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.

分析

我们可以采用题目的提示给出的serialize/deserialize的方法去做。按照depth去遍历整个数,使用队列保存遍历的结果,遇到空指针时就直接将序列化的字符串塞个"N",非空指针时就将left,right依次塞进队列中。

反序列化时,首先解析字符串,将所有的TreeNode都存进数组中,随后使用i, j 遍历字符串,i代表着父指针,j代表子指针,依次遍历每次i为null时,直接跳过,i为非空指针时,将左右指针分别指向j, j+1,j向后移两位。

Code

/**
 * 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) {
        vector<string> res;

        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty())
        {
            TreeNode* head = q.front();
            if (!head)
            {
                res.push_back("N");
            }
            else
            {
                q.push(head->left);
                q.push(head->right);
                res.push_back(std::to_string(head->val));
            }
            q.pop();
        }
        
        string str;
        for (int i=0; i < res.size(); i ++)
        {
            str.append(res[i]);
            str.append(",");
        }
        return str;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data.size() == 0 || data[0] == 'N')
            return NULL;
        
        vector<string> nodeStr;
        int lastDot = 0;
        for (int i =0; i < data.size(); i ++)
        {
            if (data[i] == ',')
            {
                string s = data.substr(lastDot, i-lastDot);
                nodeStr.push_back(s);
                lastDot = i + 1;
            }
        }
        
        vector<TreeNode*> nodeVec;
        for (int i = 0; i < nodeStr.size(); i ++)
        {
            if (nodeStr[i] == "N")
            {
                nodeVec.push_back(NULL);
            }
            else
            {
                TreeNode* p = new TreeNode(atoi(nodeStr[i].c_str()));
                nodeVec.push_back(p);
            }
        }
        
        TreeNode* root = nodeVec[0];
        int i = 1, j = 0;
        while (i < nodeVec.size())
        {
            if (nodeVec[j] == NULL)
            {
                j ++;
            }
            else
            {
                nodeVec[j]->left = nodeVec[i];
                i++;
                nodeVec[j]->right = nodeVec[i];
                i++;
                j++;
            }
        }
        return root;
    }
};

运行效率

Runtime: 32 ms

Memory Usage: 5 MB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值