使用Scala的二叉树

时间:2016-01-30 07:35:21

标签: scala binary-tree

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)

1 个答案:

答案 0 :(得分:1)

create函数中,您在nodes而不是node上进行模式匹配。一旦你解决了这个问题,你可能会意识到创建树不会返回树的顶部