///用foldLeft就可以了,我重新定义了泛型,应该比较完美了
trait Tree[+T]
/**
* 空树
*/
case object Empty extends Tree[Nothing]
/**
* 节点, 单个节点是一棵树
*/
case class Node[T](val value: T, val left: Tree[T], val right: Tree[T]) extends Tree[T]
////////////////////////
def insert[T](x: T, tree: Tree[T])(implicit order: Ordering[T]): Tree[T] = {
tree match {
case Empty => Node(x, Empty, Empty)
case Node(v, left, right) if order.gt(x, v) => Node(v, left, insert(x, right))
case Node(v, left, right) if order.lt(x, v) => Node(v, insert(x, left), right)
case Node(v, left, right) if order.equiv(x, v) => Node(v, left, right) //其实没有必要重新创建
}
}
def mkBinarySearchTree[T](list: List[T])(implicit order: Ordering[T]) = {
list.foldLeft[Tree[T]](Empty)((tree, value) => insert(value, tree))
}
def main(args: Array[String]) {
mkBinarySearchTree(List(1, 2, 3))
} |