Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 12, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/a623e08970135520021e6d44b140323d to your computer and use it in GitHub Desktop.
Save ssaurel/a623e08970135520021e6d44b140323d to your computer and use it in GitHub Desktop.
TreeNode implementation for the Twenty Questions tutorial on the SSaurel's Channel
package com.ssaurel.twentyquestions;
// We will use a Binary Tree to represent the questions
// for guessing what user thinks about
// So we need to represent tree nodes
public class TreeNode {
enum Type {
ANSWER, QUESTION // nodes are answer or question
}
public static final String QUESTION_FLAG = "Q:";
public static final String ANSWER_FLAG = "A:";
public String data;
public Type type;
// if tree node is a question, he has two children (one for yes, one for no)
public TreeNode yes;
public TreeNode no;
public TreeNode() {
}
public TreeNode(String data, Type type) {
this.data = data;
this.type = type;
}
public boolean isQuestion() {
return Type.QUESTION.equals(type);
}
public void setData(String data) {
type = Type.QUESTION;
if (data.startsWith(ANSWER_FLAG)) {
type = Type.ANSWER;
}
this.data = data.substring(2); // we remove question or answer flag
}
public void addYes(TreeNode yes) {
this.yes = yes;
}
public void addNo(TreeNode no) {
this.no = no;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment