scala使用Option实现二叉树结束节点

时间:2014-11-27 19:58:17

标签: scala

我正在尝试在二叉树中实现端节点。我想知道为什么这不起作用:

//我认为通过添加Option,我可以输入None作为允许的节点[T]。但是p1或p2都不允许我编译。我怎样才能做到这一点?

class Node[T](text: String, one: Option[Node[T]], two: Node[T]) {
  override def toString = "(" + one + ", " + two + ")"
}

object GenTest {
  def main(args: Array[String]) {
    val p1 = new Node("wait", "test", "test")
    val p2 = new Node("odd", p1, p1)

    println(p1)
  }
}

2 个答案:

答案 0 :(得分:1)

"test"不是Option[Node[String]]]。您需要创建一个叶节点,然后使用Some

将其传递给父节点
class Node[T](text: String, one: Option[Node[T]], two: Option[Node[T]]) {
  override def toString = "(" + one + ", " + two + ")"
}

val leaf = new Node[String]("test", None, None)
val p1 = new Node("wait", Some(leaf), Some(leaf))
val p2 = new Node("wait", Some(p1), Some(p1))

答案 1 :(得分:0)

首先,参数2也应该是Option [Node [T]] 第二:如果你宣布它,你需要使用选项:

class Node[T](text: String, one: Option[Node[T]], two: Option[Node[T]]) {
  override def toString = text + " (" + one + ", " + two + ")"
}

object GenTest {
  def main(args: Array[String]) {
    val p1 = new Node[String]("wait", None, None)
    val p2 = new Node("odd", Some(p1), Some(p1))

    println(p1)
  }
}