I am trying read a decision tree in from a file before creating it. I have a node class that contains 3 variables Node(message, yesNode, noNode). Message stands for either the question to be asked or the answer. yesNode stands for the link to the next node if the answer is yes and noNode stands for the link to the next node if the answer is no. An example of a file that I am trying to read is as follows:

Are you a mammal?
Are you bigger than a cat?
does it have tusks
elephant
#
#
Kangaroo
#
#
Mouse
#
#
Do you live underwater?
Trout
#
#
Robin
#
#

The file is stored in preOrder traversal and # stand for null values. I can't get my head round how i should attempt to implement this, any recommendations?

有帮助吗?

解决方案

several ways to do it, this is pseudo-java for one way:

Try something like:

class Node {
  String message;
  Node yes;
  Node no;
}

Reader myFile = new FileReader("datafile.txt"); // reads your file
Node myTree = parseNode(); // will point to the root of your tree

// This recursive function traverses (and builds) your tree.
Node parseNode() {
  Node newNode;
  String input = myFile.readline();
  if (input.equals("#)) {
    return null;
  } else {
    newNode.message = input;
    newNode.yes = parseNode();
    newNode.no = parseNode();
}

(by pseudo-java I mean it's [mostly] Java syntax, but it won't compile as-is and is meant to show the general idea.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top