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?
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:
Now, you can perform a pre-order traversal of your binary tree to populate your nodes.
Here, I expect
-1to be treated like aNULLpointer. Then, dump thebfdto 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.