Here's a naive way if you have something like:
struct bst { int val; struct bst *left;
Create another structure:
struct bst_serial { int val; int left;
Then malloc represents an array of bst_serial , the size of which is equal to your tree:
struct bst_serial *serial_bst = malloc(sizeof(struct bst_serial) * tree_size);
So make the tree walk the same (untested):
int current_pos = 0; int convert_node(bst *root) { int this_pos = current_pos; current_pos++; serial_bst[this_pos].val = root->val; if(root->left != NULL) { serial_bst[this_pos].left = convert_node(root->left); } else { serial_bst[this_pos].left = -1; } if(root->right != NULL) { serial_bst[this_pos].right = convert_node(root->right); } else { serial_bst[this_pos].right = -1; } return this_pos; }
Now you can write() output the array to disk. If you write functions to move the bst_serial tree bst_serial , you don't even need to deserialize it - you can just mmap() it. For extra points, do not even use the pointer tree in the first place - create and increase the bst_serial array when creating the binary tree. Then your code does not need to worry about whether it is related to the tree from the disk or to the tree you just created.
source share