LeetCode //C - 297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Example 1:

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []
Output: []

Constraints:
  • The number of nodes in the tree is in the range [ 0 , 1 0 4 ] [0, 10^4] [0,104].
  • -1000 <= Node.val <= 1000

From: LeetCode

Link: 297. Serialize and Deserialize Binary Tree


Solution:

Ideas:
  • Serialization:
    • We traverse the tree in pre-order.
    • Each node's value is appended to the buffer string.
    • For NULL nodes, we append "#," to indicate an absence of a child.
  • Deserialization:
    • We parse the string token by token.
    • If we encounter a "#", we return NULL for that node.
    • Otherwise, we create a new node and recursively build its left and right children.
Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
// Function to create a new tree node.
struct TreeNode* newNode(int val) {
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Helper function for serialization.
void serializeHelper(struct TreeNode* root, char* buffer, int* index) {
    if (root == NULL) {
        strcpy(&buffer[*index], "#,");
        *index += 2;
        return;
    }
    
    int len = sprintf(&buffer[*index], "%d,", root->val);
    *index += len;
    
    serializeHelper(root->left, buffer, index);
    serializeHelper(root->right, buffer, index);
}

// Encodes a tree to a single string.
char* serialize(struct TreeNode* root) {
    // Allocate a buffer to store the serialized string.
    // Size of 10000 * 6 is arbitrary, based on the problem constraints.
    char* buffer = (char*)malloc(10000 * 6);
    int index = 0;
    serializeHelper(root, buffer, &index);
    buffer[index] = '\0';
    return buffer;
}

// Helper function for deserialization.
struct TreeNode* deserializeHelper(char** data) {
    if (**data == '#') {
        *data += 2; // Skip '#,'
        return NULL;
    }
    
    int val = 0;
    int sign = 1;
    if (**data == '-') { // Check for negative numbers
        sign = -1;
        (*data)++;
    }
    while (**data != ',') {
        val = val * 10 + (**data - '0');
        (*data)++;
    }
    val *= sign;
    (*data)++; // Skip ','

    struct TreeNode* node = newNode(val);
    node->left = deserializeHelper(data);
    node->right = deserializeHelper(data);
    return node;
}

// Decodes your encoded data to tree.
struct TreeNode* deserialize(char* data) {
    return deserializeHelper(&data);
}

// Your functions will be called as such:
// char* data = serialize(root);
// deserialize(data);
相关推荐
Dr.9275 分钟前
1-10 目录树
java·数据结构·算法
双叶8368 分钟前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)(网页版预告)(html)(js)(json)
c语言·javascript·数据结构·html·json
子豪-中国机器人17 分钟前
C++ 蓝桥 STEMA 省选拔赛模拟测试题(第一套)
开发语言·c++·算法
callJJ19 分钟前
Bellman - Ford 算法与 SPFA 算法求解最短路径问题 ——从零开始的图论讲解(4)
数据结构·算法·蓝桥杯·图论·单源最短路径·bellman- ford算法
圈圈编码22 分钟前
LeetCode Hot100刷题——轮转数组
java·算法·leetcode·职场和发展
金融小师妹5 小时前
应用BERT-GCN跨模态情绪分析:贸易缓和与金价波动的AI归因
大数据·人工智能·算法
广州智造5 小时前
OptiStruct实例:3D实体转子分析
数据库·人工智能·算法·机器学习·数学建模·3d·性能优化
belldeep6 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
Trent19857 小时前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo1237 小时前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类