使用Scala的二叉树
我正在尝试使用scala创建一棵树。但这是行不通的。它显示堆栈溢出错误 [信息]java.lang.StackOverflower错误: [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21)使用Scala的二叉树,scala,binary-tree,Scala,Binary Tree,我正在尝试使用scala创建一棵树。但这是行不通的。它显示堆栈溢出错误 [信息]java.lang.StackOverflower错误: [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.MyBst.insert(MyBst.scala:21) [信息]位于binarySearchTree.My
在
create
函数中,在节点上进行模式匹配,而不是在节点上进行模式匹配。一旦解决了这个问题,您可能会意识到createTree不会返回树的顶部我称之为createTree(list)。列表中有一些值:堆栈溢出表示调用堆栈太大,超出了可用内存。这很可能是由于递归中的错误。
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])