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

后端 未结 8 2019

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:35

    Not sure it's elegant, but it's simple and explainable: Assign a unique ID to each node, whether stem or leaf. A simple counting integer will do.

    When saving to disk, traverse the tree, storing each node ID, "yes" link ID, "no" link ID, and the text of the question or answer. For null links, use zero as the null value. You could either add a flag to indicate whether question or answer, or more simply, check whether both links are null. You should get something like this:

    1,2,3,"Does it have wings?"
    2,0,0,"a bird"
    3,4,0,"Does it purr?"
    4,0,0,"a cat"
    

    Note that if you use the sequential integers approach, saving the node's ID may be redundant, as shown here. You could just put them in order by ID.

    To restore from disk, read a line, then add it to the tree. You will probably need a table or array to hold forward-referenced nodes, e.g. when processing node 1, you'll need to keep track of 2 and 3 until you can fill in those values.

提交回复
热议问题