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])
I m trying to create a tree using scala. But this is not working. It is showing 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)