Topics / Data Structures & Algorithms / Q27
Serialize and deserialize a binary tree in C.
Short answer: Store a preorder sequence with explicit null markers so both tree structure and values are preserved. Use a fixed node pool while rebuilding.
#include <stdbool.h>
#include <stddef.h>
struct tree {
int key;
struct tree *left, *right;
};
struct token { bool present; int key; };
bool encode(const struct tree *r, struct token *a,
size_t cap, size_t *i)
{
if (*i >= cap) return false;
a[(*i)++] = (struct token){r != NULL, r ? r->key : 0};
return !r || (encode(r->left, a, cap, i) &&
encode(r->right, a, cap, i));
}
bool decode(const struct token *a, size_t n, size_t *i,
struct tree *pool, size_t cap, size_t *used,
struct tree **out)
{
if (*i >= n) return false;
struct token t = a[(*i)++];
*out = NULL;
if (!t.present) return true;
if (*used >= cap) return false;
struct tree *r = &pool[(*used)++];
r->key = t.key;
if (!decode(a,n,i,pool,cap,used,&r->left) ||
!decode(a,n,i,pool,cap,used,&r->right)) return false;
*out = r;
return true;
}
A root 7 with left child 3 encodes as 7,3,NULL,NULL,NULL. Start all counters at zero and accept decoded output only on success with all tokens consumed; discard partial output on failure. Time O(n), recursion O(h). Bound depth for untrusted input. The token array is an in-memory representation, not a portable byte format.