码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】【树】37.序列化二叉树

时间:2020-04-17 09:56:38      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:==   int   instant   struct   decode   new t   auto   cal   string   

递归

前序遍历序列化成字符串,在反序列化回去
/**
 * 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;
        dfs_s(root, res);
        return res;
    }
    void dfs_s(TreeNode* root, string &res)
    {
        if(!root) {
            res += "null ";
            return ;
        }
        res += to_string(root->val) + ‘ ‘;
        dfs_s(root -> left, res);
        dfs_s(root -> right, res);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int u = 0;
        return dfs_d(data, u);
    }

    TreeNode* dfs_d(string data, int &u)
    {
        if(u == data.size()) return NULL;
        int k = u;
        while(data[k] != ‘ ‘) k++;
        if(data[u] == ‘n‘){
            u = k + 1;
            return NULL;
        }
        int val = 0;
        if(data[u] == ‘-‘){
            for (int i = u+1; i < k; i++) val = val * 10 + data[i] - ‘0‘;
            val  = -val;
        }
        else{
        //如果是数字是正的
            for (int i = u; i < k; i++) val = val * 10 + data[i] - ‘0‘;
        }
        u = k + 1;
        auto root = new TreeNode(val);
        root -> left = dfs_d(data, u);
        root -> right = dfs_d(data, u);
        return root;
    }
};

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

【剑指offer】【树】37.序列化二叉树

标签:==   int   instant   struct   decode   new t   auto   cal   string   

原文地址:https://www.cnblogs.com/Trevo/p/12717449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!