zoukankan      html  css  js  c++  java
  • 剑指OFFER 序列化二叉树

    剑指OFFER 序列化二叉树

    弄了半天在剑指OFFER OJ上无法通过(猜测可能是因为剑指OFFER上使用的是char类型的指针,导致有一些编译的不一致问题),同样的代码在leetcode上通过了

    代码

    /**
     * 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:
        int pos = 0;
        string str;
        string res;
    
        void recur_from_order(TreeNode* &node)
        {
            if(str[pos] == '#'){
                node = NULL;
                return;
            }else{
                string str_num;
                while(str[pos] != '!')
                {
                    str_num += str[pos];
                    pos++;
                }
                //int num = stoi(str_num);
                int num = atoi(str_num.c_str());
                node = (TreeNode*)malloc(sizeof(TreeNode));
                node->val = num;
            }
            pos++;
            recur_from_order(node->left);
            pos++;
            recur_from_order(node->right);
        }
        
        void recur_to_order(TreeNode *node)
        {
            if(node == NULL){
                res += '#';
                return;
            }else{
                res += to_string(node->val);
                res += '!';
            }
            recur_to_order(node->left);
            recur_to_order(node->right);
        }
        
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            recur_to_order(root);
            return res;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            str = data;
            TreeNode* ret;
            recur_from_order(ret);
            return ret;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    

    采用的先序遍历的方式,先写序列化的代码,就是先序遍历一遍,遇到结点就记录到res中.

    反序列化稍微复杂一点,聚焦于两个状态,一个是结点,一个是字符串的位置指针,通过这两个状态来构建二叉树.

  • 相关阅读:
    2,进程----multiprocessing模块介绍
    1,进程----进程理论知识
    对ORM的理解
    对queryset的理解
    个人总结-10-代码测试整合
    个人总结-9-session的使用,十天免登陆
    个人总结-8-重新写注册和登录界面
    个人总结-7- 实现图片在MySQL数据库中的存储,取出以及显示在jsp页面上
    从人机交互看对搜狗输入法的使用感受
    个人总结6-验证码制作总结
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12234806.html
Copyright © 2011-2022 走看看