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

  • 相关阅读:
    织梦开发——相关阅读likeart应用
    织梦标签教程
    织梦专题调用代码
    HIT 2543 Stone IV
    POJ 3680 Intervals
    HIT 2739 The Chinese Postman Problem
    POJ 1273 Drainage Ditches
    POJ 2455 Secret Milking Machine
    SPOJ 371 Boxes
    HIT 2715 Matrix3
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8900903.html
Copyright © 2011-2022 走看看