在SCALA中创建二叉树

时间:2018-07-21 11:14:20

标签: scala tree binary

scala> def buildTree[A](list:List[A]):BinTree[A]=list match{
     | case Nil=>Leaf
     | case x :: xs =>{
     | val k = xs.length/2
     | Branch(x,buildTree(xs.take(k)),buildTree(xs.drop(k))
     | )
     | }
     | }

但它的说法是:-错误:未找到:键入BinTree                 :-错误:找不到:值分支                 :-错误:找不到:值Leaf

1 个答案:

答案 0 :(得分:2)

您可能想要这样的东西:

trait BinTree[+A]
case object Leaf extends BinTree[Nothing]
case class Branch[+A](node: A, left: BinTree[A], right: BinTree[A]) extends BinTree[A]

def buildTree[A](list: List[A]): BinTree[A] = list match {
 case Nil => Leaf
 case x :: xs =>
    val (left, right) = xs.splitAt(xs.length/2)

    Branch(x, buildTree(left), buildTree(right))
}

但是在尝试像这样的更复杂的东西之前,您确实需要熟悉Scala的一些基础知识。