【发布时间】:2021-05-04 15:56:58
【问题描述】:
我是 Scala 的初学者。所以我的问题可能很愚蠢,请耐心等待。 我有一个二叉树结构的模板:
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]
我想编写一个从列表创建二叉树的函数。第一个列表元素是根。分支左侧的所有数据都较小,分支右侧的所有数据都较大:
def listToTree[T](list: List[T]): Tree[T]
我不确定我写错了什么,但我的输出总是只有第一个 List 元素
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)
}
所以最终正确的输出应该是这样的:
val list = List(3, 2, 4, 1)
assert(listToTree(list) == Branch(Branch(Branch(Leaf(),1,Leaf()),2,Leaf()))),3,Branch(Leaf(),4,Leaf()))
【问题讨论】:
标签: scala data-structures binary-tree