zoukankan      html  css  js  c++  java
  • leetcode297 Serialize and Deserialize Binary Tree

    思路:

    前序遍历 + 空节点标记。

    实现:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Codec
    11 {
    12 public:
    13 
    14     // Encodes a tree to a single string.
    15     string serialize(TreeNode* root)
    16     {
    17         if (!root) return "x";
    18         return to_string(root->val) + ',' + serialize(root->left) + ',' + serialize(root->right);
    19     }
    20 
    21     // Decodes your encoded data to tree.
    22     TreeNode* deserialize(string data)
    23     {
    24         data += ',';
    25         int l = data.length();
    26         queue<string> q; int last = 0;
    27         for (int i = 0; i < l; i++)
    28         {
    29             if (data[i] == ',')
    30             {
    31                 q.push(data.substr(last, i - last));
    32                 last = i + 1;
    33             }
    34         }
    35         return work(q);
    36     }
    37     
    38     TreeNode* work(queue<string>& q)
    39     {
    40         string t = q.front(); q.pop();
    41         if (t == "x") return NULL;
    42         TreeNode* res = new TreeNode(stoi(t));
    43         res->left = work(q);
    44         res->right = work(q);
    45         return res;
    46     }
    47 
    48 };
    49 
    50 // Your Codec object will be instantiated and called as such:
    51 // Codec codec;
    52 // codec.deserialize(codec.serialize(root));
  • 相关阅读:
    js this
    python词云的制作方法
    flask表单标签
    scrapy使用PhantomJS爬取数据
    flask连接sqlalchemy数据库,实现简单的登录跳转功能
    useful tools and website
    sqlalchemy精华版
    flask连接数据库mysql+SQLAlchemy
    flask框架get post方式
    flask基础知识
  • 原文地址:https://www.cnblogs.com/wangyiming/p/11148989.html
Copyright © 2011-2022 走看看