• 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));
  • 相关阅读:
    IDEA安装步骤
    记录常用网站
    IDEA解决中文乱码问题
    使用IDEA 中 实现springboot 热部署 (spring boot devtools版)
    Springboot学习
    写文档步骤
    some untracked working tree files问题解决
    利用mybatis-generator自动生成代码
    Java实现打印功能
    sql语句大全
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9076445.html
Copyright © 2020-2023  润新知