当前位置: 首页 > article >正文

C语言 | Leetcode C语言题解之第449题序列化和反序列化二叉搜索树

题目:

题解:

#define MAX_NODE_SIZE 10000

void postOrder(struct TreeNode *root, int *arr, int *pos) {
    if (root == NULL) {
        return;
    }
    postOrder(root->left, arr, pos);
    postOrder(root->right, arr, pos);
    arr[(*pos)++] = root->val;
}

struct TreeNode * construct(int lower, int upper, int *stack, int *top) {
    if (*top == 0 || stack[*top - 1] < lower || stack[*top - 1] > upper) {
        return NULL;
    }
    int val = stack[*top - 1];
    (*top)--;
    struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    root->val = val;
    root->right = construct(val, upper, stack, top);
    root->left = construct(lower, val, stack, top);
    return root;
}

char* serialize(struct TreeNode* root) {
    char *res = NULL;
    int *arr = (int *)malloc(sizeof(int) * MAX_NODE_SIZE);
    int pos = 0;
    postOrder(root, arr, &pos);
    if (pos == 0) {
        return "";
    }
    res = (char *)malloc(sizeof(char) * pos * 6);
    int len = 0;
    for (int i = 0; i < pos - 1; i++) {
        len += sprintf(res + len, "%d,", arr[i]);
    }
    sprintf(res + len, "%d", arr[pos - 1]);
    free(arr);
    return res;
}

struct TreeNode* deserialize(char* data) {
    int len = strlen(data);
    if (len == 0) {
        return NULL;
    }
    int *stack = (int *)malloc(sizeof(int) * MAX_NODE_SIZE);
    int pos = 0;
    int top = 0;
    while (pos < len) {
        while (pos < len && data[pos] == ',') {
            pos++;
        }
        int val = 0;
        int start = pos;
        while (pos < len && data[pos] != ',') {
            val = val * 10 + data[pos] - '0';
            pos++;
        }
        if (start < pos) {
            stack[top++] = val;
        }
    }
    struct TreeNode *root = construct(INT_MIN, INT_MAX, stack, &top);
    free(stack);
    return root;
}

http://www.kler.cn/news/335129.html

相关文章:

  • 【Conda】修复 Anaconda 安装并保留虚拟环境的详细指南
  • Spring的热部署工具和数据库密码加盐操作
  • paper_template
  • 深度学习-20-深入理解基于Streamlit和minimind小模型开发本地聊天工具
  • 系统架构设计师⑦:企业信息化战略与实施
  • 第三十五章 结合加密和签名
  • 第二十三章-容器控件QTabWidget
  • vue2集成tailwind.css,快速开发前台页面
  • 深度学习:迁移学习
  • Spire.PDF for .NET【页面设置】演示:设置 PDF 的查看器首选项和缩放系数
  • o1-preview 在 IMO 2024 第一题的实测表现
  • 系统架构设计师论文《论SOA在企业集成架构设计中的应用》精选试读
  • javaScript数组(16个案例+代码+效果图)
  • 安装配置pytorch(cuda、、cudnn、torch、torchvision对应版本)
  • 大数据利器Hadoop:从基础到实战,一篇文章掌握大数据处理精髓!
  • 已解决:org.springframework.web.HttpMediaTypeNotAcceptableException
  • 免费!推荐10个可商用模特图片素材网站!
  • 实现Xshell与虚拟机中Linux服务器的连接(附常见错误解决)
  • vite学习教程06、vite.config.js配置
  • 54.二叉树的最大深度