I'm a complete beginner in Scala. So my question might be quite stupid, please be patient with me. I have a template for a binary tree structure:
sealed trait Tree[T]
case class Leaf[T]() extends Tree[T]
case class Node[T](left: Tree[T], data :Int, right Tree[T]) extends Tree[T]
I want to write a function which creates a binary tree from a list. The first list element is the root. All data left of a branch are smaller and all data right of a branch are bigger:
def listToTree[T](list: List[T]): Tree[T]
I'm not sure what I wrote wrong, but my output is always only the first List element
def setElement(x: Int, tree: Tree[Int]): Tree[Int] = tree match {
case Node(l, e, r) => Node(l, x, r)
case Leaf() => new Node(Leaf(), x, Leaf())
}
def listToTree2[T](as: List[Int], tree: Tree[Int], x: Int): Tree[Int] = tree match
{
case Leaf() => listToTree2(as.tail, setElement(as.head, tree), x)
case Node(left, e, right) => if(e < x) {
right match {
case Leaf() => listToTree2(as.tail, setElement(as.head, tree), x)
case Node(left2, e2, right2) => if( e < e2) listToTree2(as, right, x)
else listToTree2(as, left, x)
}
} else if(e > x) {
left match {
case Leaf() => listToTree2(as.tail, setElement(as.head, tree), x)
case Node(left3, e3, right3) => if( e < e3) listToTree2(as, right, x) else listToTree2(as, left, x)
}
} else {
listToTree2(as.tail, tree, x)
}
}
def listToTree[T](as: List[Int]): Tree[Int] =
{
val tree = new Node(Leaf(), as.head, Leaf())
listToTree2(as, tree, as.head)
}
So in the end the correct output should be something like this:
val list = List(3, 2, 4, 1)
assert(listToTree(list) == Branch(Branch(Branch(Leaf(),1,Leaf()),2,Leaf()))),3,Branch(Leaf(),4,Leaf()))