I''ve got a struct like this:

struct Node
{ int n;
Node *left;
Node *right;
}

I build up a binary tree from this struct. Now, how can i save the binary tree onto the hard disk, and how can i rebuild it from the hard disk ?

You would use the output of your tree traverse function and construct the tree next time with your corresponding constructor from same traversal order. Also you could name the nodes and list the children of each node and identify the top node (say the first one in the list). This is generally considered more practical way for trees than actual concreate linked structure (in addition of the adjacency matrix, which you also can use to save, but it is highly redundant and sparse).

Now, how can i save the binary tree onto the hard disk, and how can i rebuild it from the hard disk ?

Well, obviously you need to devise some kind of format, but the easiest method is with record ordering. You can treat serialization as an extension of copying, where a pre-order traversal is the way to go:

void serialize_tree(FILE *out, node *root)
{
    if (root != NULL) {
        fprintf(out, "%s\n", to_string(root->data));
        serialize_tree(out, root->left);
        serialize_tree(out, root->right);
    }
}

When reading back from the file, the records are already in an order conducive for reproducing the original tree:

void deserialize_tree(FILE *in, node *root)
{
    char buf[BUFSIZ];

    while (fgets(buf, sizeof buf, in) != NULL)
        root = insert(root, from_string(buf));
}

so tnx :)
but how can i saving binary tree onto the hard with fseek functions ??

how can i saving binary tree onto the hard with fseek functions ??

Why would you want to do that when it's completely unnecessary?

I want to learn it :) can u help me?
plzzzzzzzzzzzzzzzzzz

Edited 5 Years Ago by shimooli: n/a

@Narue

How does the method described by you handle the case when the binary tree is not complete ie. Some of the intermediate nodes could have 0 (or 1) children

How does the method described by you handle the case when the binary tree is not complete

As long as the original tree is a valid binary search tree, the restored tree will be an exact copy. The down side of this method is reconstructing the tree is O(N log N) because it reuses the insert operation. There are ways around that, but it's not as concise.

This article has been dead for over six months. Start a new discussion instead.