Scala中的二叉树

时间:2013-11-28 14:28:25

标签: scala list tree binary-tree

我正在尝试编写一个将转换二叉树整数列表的函数。这是我的代码:

sealed trait btree[+A]
case class Empty extends btree[Nothing]
case class Node[+A](elem: A, left : btree[A], right : btree[A]) extends btree[A]

def list2btree(list : List[Int]) : btree[Int] = {
def insert2tree(x : Int, t : btree[Int]) : btree[Int] = {
    (x, t) match {
        case (x, Empty) => Node(x, Empty, Empty)
        case (x, Node(v, left, right)) => {
            if(v > x) Node(v, insert2tree(x, left), right)
            else if(v < x) Node(v, left, insert2tree(x,right))
            else throw new Exception("Element exsist!")
        }
    }
}

list match {
    case Nil => Empty
    case (h::t) => insert2tree(h, list2btree(t))
}
}

但它不起作用。你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

Empty不需要是一个类,它应该只是一个对象:

sealed trait btree[+A]
case object Empty extends btree[Nothing]
case class Node[+A](elem: A, left : btree[A], right : btree[A]) extends btree[A]

然后您的代码有效(尽管您以相反的顺序添加元素,这可能不是您想要的):

scala> list2btree(List(6,2,3,1,4))
res0: btree[Int] = Node(4,Node(1,Empty,Node(3,Node(2,Empty,Empty),Empty)),Node(6,Empty,Empty))

编辑: 在错误本身上,如果Empty是案例类,则需要()之后指定您想要Empty类的实例:

scala> case class Empty
<console>:1: warning: case classes without a parameter list have been deprecated;
use either case objects or case classes with `()' as parameter list.

scala> Empty
res0: Empty.type = Empty

scala> Empty()
res1: Empty = Empty()