如何编写此算法以在问题树中搜索下一个问题?

时间:2019-06-18 05:20:13

标签: javascript tree binary-search-tree

我一直在努力为此编写正确的算法。所以我有一棵看起来像这样的问题树:

[
  {
    question: "Question 1",
    answers: {
      "yes": [
        {
          question: "Question 1a",
          answers: ["A", "B"]
        }
      ],
      "no": null
    }
  },
  {
    question: "Question 2",
    answers: ["I agree"]
  }
]

我有一个responses对象,看起来像这样:

[
  { question: "Question 1", answer: "yes" },
  { question: "Question 1a", answer: "B" },
]

或者可能是这样:

[
  { question: "Question 1", answer: "no" },
]

现在我正在努力编写的代码是要找出下一个问题。 responses对象的以上两个示例都应指向下一个问题"Question 2"

我想要一个类似getNextQuestion(questions, responses)的函数,然后希望输出:

{
  question: "Question 2",
  answers: ["I agree"]
}

我已经找到了如何下那棵树,但是当有必要的时候我无法弄清楚如何下这棵树。有人愿意帮助吗?

1 个答案:

答案 0 :(得分:0)

嗯,我可能已经用此代码修复了它。到目前为止,一切正常。

getCurrentQuestion(questions, responses) {
  if (!responses.length || !questions.length) {
    return questions.length ? questions[0] : null
  }

  let response = responses.shift()
  let question

  do {
    question = questions.shift()
  } while (question.question !== response.question)

  let answer = question.answers[response.answer]

  return this.getCurrentQuestion(answer || questions, responses)
    || this.getCurrentQuestion(questions, responses)
}