class MyBst {
def createTree(list:List[Int]): Node={
require(list.nonEmpty)
val nodes = list.map(element => Node(None, element, None))
val root = nodes.head
def create(node:List[Node], tree:Node):Node=
nodes match{
case head::tail => create(tail,insert(tree,head))
case Nil => tree
}
create(nodes.tail,root)
}
def insert(tree:Node,elem:Node):Node = {
if(tree.data >= elem.data)
if(tree.left.isDefined)
tree.copy(left = Some(insert(tree.left.get,elem)))
else
tree.copy(left = Some(elem))
else
if(tree.right.isDefined)
tree.copy(right = Some(insert(tree.right.get,elem)))
else
tree.copy(right=Some(elem))
}
}
case class Node(left:Option[Node], data:Int, right:Option[Node])
我正在尝试使用scala创建一个树。但这不起作用。它显示Stack Over Flow Error。
[info] java.lang.StackOverflowError:
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
[info] at binarySearchTree.MyBst.insert(MyBst.scala:21)
答案 0 :(得分:1)
在create
函数中,您在nodes
而不是node
上进行模式匹配。一旦你解决了这个问题,你可能会意识到创建树不会返回树的顶部