In short, I\'d like to learn/develop an elegant method to save a binary tree to disk (a general tree, not necessarily a BST). Here is the description of my problem:
I\'
I would do a Level-order traversal. That is to say you are basically doing a Breadth-first search algorithm.
You have:
Level-order traversal sequence: F, B, G, A, D, I, C, E, H
What you will store on disk: F, B, G, A, D, NullNode, I, NullNode, NullNode, C, E, H, NullNode
Loading it back from disk is even easier. Simply read from left to right the nodes you stored to disk. This will give you each level's left and right nodes. I.e. the tree will fill in from top to bottom left to right.
Step 1 reading in:
F
Step 2 reading in:
F
B
Step 3 reading in:
F
B G
Step 4 reading in:
F
B G
A
And so on ...
Note: Once you have a NULL node representation, you no longer need to list its children to disk. When loading back you will know to skip to the next node. So for very deep trees, this solution will still be efficient.