zoukankan      html  css  js  c++  java
  • 297. Serialize and Deserialize Binary Tree

    /**
     * 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;
            serialize(root, res);
            return res;
        }
        void serialize(TreeNode* root, string &res) {
            if (root == NULL) {
                res += "#,";
                return;
            }
            res += to_string(root->val) + ",";
            serialize(root->left, res);
            serialize(root->right, res);
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            int idx = 0;
            return deserialize(data, idx);
        }
        TreeNode* deserialize(const string& data, int& idx) {
            if (idx >= data.length()) return NULL;
            int start = idx;
            while (data[idx] != ',')    idx++;
            string token = data.substr(start, idx-start);
            if (token == "#")   return NULL;
            TreeNode *root = new TreeNode(stoi(token));
            
            idx++;
            root->left = deserialize(data, idx);
            idx++;
            root->right = deserialize(data, idx);
            return root;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
  • 相关阅读:
    mongoDB常用命令
    Linux下安装MongoDB
    Linux下mysq基础命令(二)
    Linux下mysql基础命令(一)
    Linux 下使用yum 命令安装MySQL
    Linux 常用命令
    windows7用WMware安装Linux虚拟机详细步骤
    接口测试全流程扫盲
    Jmeter时间格式化
    Jmeter之测试报告
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9076445.html
Copyright © 2011-2022 走看看