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

  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8900903.html
Copyright © 2011-2022 走看看