zoukankan      html  css  js  c++  java
  • leecode第二百九十七题(二叉树的序列化与反序列化)

    /**
     * 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) {//结果并不是层序
            if (root == NULL)
                return "#_";
            string res = to_string(root->val) + "_";
            res += serialize(root->left);
            res += serialize(root->right);
            return res;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {//先打入一个队列里
            stringstream ss(data);
            string item;
            queue<string> q;
            while (getline(ss, item, '_')) 
                q.push(item);
            return helper(q);
        }
        
        TreeNode* helper(queue<string>& q)//对队列进行反序列化
        {
            string val = q.front();
            q.pop();
            if (val == "#")
                return NULL;
            TreeNode* head = new TreeNode(stoi(val));
            head->left = helper(q);
            head->right = helper(q);
            return head;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));

    分析:

    层序遍历。

  • 相关阅读:
    k线图
    Sql Server中查看所有数据库,表名,字段名以及字段类型
    通过datetime模块获取几秒,几分钟,几天前的时间
    线程池回调函数实时调用返回值
    pandas操作excel
    read_excle
    to_excel
    set_index
    DataFrame
    Python笔记003-字符串(1)
  • 原文地址:https://www.cnblogs.com/CJT-blog/p/11288837.html
Copyright © 2011-2022 走看看