题解 | #序列化二叉树#

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

class Solution {
  public:
    char* Serialize(TreeNode* root) {
        queue<TreeNode*> nodes;
        nodes.push(root);
        string ret;
        while (!nodes.empty()) {
            auto cur_node = nodes.front();
            nodes.pop();
            if (cur_node == nullptr)
                ret += "#,";
            else {
                ret += to_string(cur_node->val);
                ret += ',';
                nodes.push(cur_node->left);
                nodes.push(cur_node->right);
            }
        }
        char* result = strdup(ret.c_str());
        return result;
    }
    TreeNode* Deserialize(char* str) {
        if ((str == nullptr) || (*str == '\0'))
            return nullptr;
        string orig = str;
        queue<string> backlog;
        queue<TreeNode**> tree;
        const char delimiter = ',';
        ssize_t pos;
        while ((pos = orig.find(delimiter)) != string::npos) {
            backlog.push(orig.substr(0, pos));
            orig.erase(0, pos + 1);
        }
        auto head = stonode(backlog.front());
        backlog.pop();
        if (head != nullptr) {
            tree.push(&(head->left));
            tree.push(&(head->right));
        }
        while (!backlog.empty()) {
            auto cur_node = tree.front();
            tree.pop();
            *cur_node = stonode(backlog.front());
            backlog.pop();
            if ((*cur_node) != nullptr) {
                tree.push(&((*cur_node)->left));
                tree.push(&((*cur_node)->right));
            }
        }
        return head;
    }
  private:
    TreeNode* stonode(const string& str) {
        if (str.compare("#") == 0)
            return nullptr;
        else
            return new TreeNode(stoi(str));
    }
};
巧用指向left和right的指针(TreeNode**)来实现层序遍历的反序列化。
全部评论

相关推荐

点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务