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

    ###题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 ###代码

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
        char* Serialize(TreeNode *root) {//bfs
            string ans;
            if (root != NULL) {
                queue<TreeNode*> que;
    
                que.push(root);
                TreeNode* cur;
                while (!que.empty()) {
                    cur = que.front();
                    que.pop();
                    if (cur == NULL) {
                        ans += '#';
                    } else {
                        if (ans.size() > 0 && ans[ans.size() - 1] != ' ' && ans[ans.size() - 1] != '#') {
                            ans += ' ';
                        }
                        ans += to_string(cur->val);
    
                        que.push(cur->left);
                        que.push(cur->right);
                    }
                }
    
            }
            char *result = new char[ans.size() + 1];
            for (int i = 0; i < ans.size(); ++i) {
                result[i] = ans[i];
            }
            result[ans.size()] = '';
            return result;
    
        }
        TreeNode* Deserialize(char *str) {//bfs
            TreeNode* root = NULL;
            if (str[0] != '') {
                queue<TreeNode*> que;
                int s = 0;
                root = newNode(str, s);
                que.push(root);
                TreeNode* cur;
                while (str[s] != '') {
                    cur = que.front();
                    que.pop();
    
                    if (isdigit(str[s]) || str[s++] == ' ') {
                        TreeNode* left = newNode(str, s);
                        cur->left = left;
                        que.push(left);
                    }
    
                    if (str[s] != '' && (isdigit(str[s]) || str[s++] == ' ')) {
                        TreeNode* right = newNode(str, s);
                        cur->right = right;
                        que.push(right);
                    }
                }
    
            }
            return root;
        }
    
        TreeNode* newNode(char *str, int &s) {
            string num;
            while (str[s] != '' && str[s] != ' ' && str[s] != '#') {
                num += str[s];
                ++s;
            }
            return new TreeNode(stoi(num));
        }
    };
    
  • 相关阅读:
    HDU 3152 Obstacle Course(BFS+优先队列 重载)
    芸芸毕业生
    shell学习三十四天----printf具体解释
    tomcat启动批处理——catalina.bat
    ZooKeeper启动过程2:FastLeaderElection
    R语言——数据分析的一把利剑
    Oracle blob字段的插入和更新
    [LeetCode] 698. Partition to K Equal Sum Subsets
    小知识!
    小知识!
  • 原文地址:https://www.cnblogs.com/jecyhw/p/6652378.html
Copyright © 2011-2022 走看看