Want to save binary tree to disk for “20 questions” game

后端 未结 8 2013

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\'

8条回答
  •  盖世英雄少女心
    2021-02-06 15:37

    I would do a Level-order traversal. That is to say you are basically doing a Breadth-first search algorithm.

    You have:

    1. Create a qeueue with the root element inserted into it
    2. Dequeue an element from the queue, call it E
    3. Add the left and right children of E into the queue. If there is no left or right, just put a null node representation.
    4. write node E to disk.
    5. Repeat from step 2.

    alt text

    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.

提交回复
热议问题