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));
  • 相关阅读:
    Java修饰符
    java中接口的定义
    抽象类
    final关键字的特点
    hdu6489 2018 黑龙江省大学生程序设计竞赛j题
    POJ 3268 (dijkstra变形)
    poj 2253 floyd最短路
    poj1681 Network
    bzoj1202 狡猾的商人
    Nastya Is Buying Lunch
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9076445.html
Copyright © 2011-2022 走看看