简体   繁体   中英

How to convert inorder(LDR) binary tree packed in an array back to binary tree in C+working with files

Consider I already have a function called int* binToArrayInOrder(TreeRoot* tr) which creates a sorted array of tree values (because it's in order).

Is there anyway to construct back the tree from the in order given array, without other information such as the same tree representation in pre order array?

How can I write the array to a text file in C, please show me code.

[1] You can reinsert the array elements into a binary tree again. Depending on the balancing algorithm, the tree may not look exactly like it did when you extracted them into the array, though.

[2] How about this?

void print_array (int *array, size_t sz, FILE *f) {
    if (!sz) return;
    fprintf(f, "%d\n", *array);
    print_array(array+1, sz-1, f);
}

From your comments, your actual question is how to save a binary tree to disk, and then restore it. This is a data structure serialization problem. For this problem, an in-order walk is probably not what you want. Instead, the serialization should reflect how the data structure is laid out. So, you need a record that describes a binary node:

struct binary_node_file_data {
    char data_[MAX_BINARY_NODE_DATA_SIZE];
    int parent_;
};

Now, you can perform a pre-order traversal of your binary tree to populate your nodes.

struct binary_node_fila_data *bfd = malloc(sizeof(*bfd)*nodeCount);
int count = 0;
populate_binary_node_file(tree, bfd, &count, -1);

void populate_binary_node_file(binary_tree_t *tree,
                               struct binary_node_file_data *bfd,
                               int *count,
                               int parent) {
    if (tree) {
        int me = *count;
        *count += 1;
        export_binary_node_data(tree, &bfd[me], parent);
        populate_binary_node_file(tree->left_subtree, bfd, count, me);
        populate_binary_node_file(tree->right_subtree, bfd, count, me);
    }
}

Here, I expect -1 to be treated like a NULL pointer. Then, dump the bfd to a file. I'll leave restoring the tree as an exercise. Reflecting on the problem a little more, it doesn't really matter if the traversal is pre-order or in-order (or post-order). The restoration step just needs to be able to allow all the children to find the parent so that they can populate the left and right pointers properly.

For the first question: no, an inorder list of nodes doesn't allow you to reconstruct the same tree.

For example, the tree

  3
 2
1

produces the inorder traversal 1 2 3

The tree

 2
1 3

also produces 1 2 3. Thus, you can't tell which tree was used to produce a given 1 2 3.

For the second question: I haven't used STL file I/O yet, sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM