zoukankan      html  css  js  c++  java
  • 449 Serialize and Deserialize BST 序列化和反序列化二叉搜索树

    详见:https://leetcode.com/problems/serialize-and-deserialize-bst/description/

    C++:

    /**
     * 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) {
            ostringstream os;
            serializeHelper(root,os);
            return os.str();
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream is(data);
            return deserializeHelper(is);
        }
        void serializeHelper(TreeNode* root,ostringstream &os)
        {
            if(!root)
            {
                os<<"# ";
            }
            else
            {
                os<<root->val<<" ";
                serializeHelper(root->left,os);
                serializeHelper(root->right,os);
            }
        }
        TreeNode* deserializeHelper(istringstream &is)
        {
            string val;
            is>>val;
            if(val=="#")
            {
                return nullptr;
            }
            TreeNode* node=new TreeNode(stoi(val));
            node->left=deserializeHelper(is);
            node->right=deserializeHelper(is);
            return node;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    

     参考:https://www.cnblogs.com/grandyang/p/6224510.html

  • 相关阅读:
    星空Password
    股票交易
    【1】博客目录
    事务
    C#基础索引
    C# String
    MSIL
    Evaluation Stack
    Spring源码编译以及导入Intellij IDEA的操作步骤
    WebFlux响应式编程简单示例
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8900903.html
Copyright © 2011-2022 走看看