0

I am trying to implement end nodes in my Binary Tree. I am wondering why this doesnt work:

// I thought that by adding Option, I can enter None as an allowed Node[T]. But neither p1 or p2 allows me to compile. How can I make this work?

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 Answers 2

1

"test" is not an Option[Node[String]]]. You need to create a leaf node and then pass it to the parent using 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))
Sign up to request clarification or add additional context in comments.

5 Comments

hey, can you explain that to me? Also this doesn't work. It refuses to compile saying: found : Some[Node[Nothing]] required: Option[Node[T]]
@user1639926 - You need to change the type of two to be Option[Node[T]] as well, see update.
i did, the error is occuring p1: Error:(12, 51) type mismatch; found : Some[Node[Nothing]] required: Option[Node[T]] val p1 = new Node("wait", Some(leaf), Some(leaf)) ^
@user1639926 - Sorry, you also need to supply the type of T when creating leaf, updated.
why do you need to supply type T in leave but not in p1 or p2?
0

First of all parameter two should also be Option[Node[T]].
Second: You need to use option if you declared it:

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)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.