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

后端 未结 8 2012

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

    You can store it recursively:

     void encodeState(OutputStream out,Node n) {
            if(n==null) {
                out.write("[null]");
            } else {
               out.write("{");
               out.write(n.nodeDetails());
               encodeState(out, n.yesNode());
               encodeState(out, n.noNode());
               out.write("}");
            }
      }
    

    Devise your own less texty output format. I'm sure I don't need to describe the method to read the resulting output.

    This is depth-first traversal. Breadth-first works too.

提交回复
热议问题