2014-01-29 85 views
0

我在斯卡拉實現一個基本的二叉樹。我正在實現插入,並遇到我的遞歸函數在尚未初始化的節點上調用自身的問題。斯卡拉遞歸和單位

// binarytree.scala 
sealed abstract class Tree { 
    def insert(_value: Int) 
} 

case class Node(value: Int, left: Tree, right: Tree) extends Tree { 
    def insert(_value: Int) = 
    if (_value < value) Node(value, left.insert(_value), right) 
    else Node(value, left, right.insert(_value)) 
} 

case object End extends Tree { 
    def insert(_value: Int) = Node(_value) 
} 

object Node { 
def apply(_value: Int): Node = Node(_value, End, End) 
} 

var bt = Node(3) 
println(bt.insert(4)) 

我的實現使用End節點來表示尚未實例化的節點。我認爲這將避免我得到的確切錯誤。這裏是left.insert()的錯誤日誌:

error: type mismatch; 
    found : Unit 
    required: this.Tree 
    if (_value < value) Node(value, left.insert(_value), right) 

有沒有人有任何建議?

回答

1

你只需要批註插入的Tree類中的返回類型:

sealed abstract class Tree { 
    def insert(_value: Int) : Node 
} 

它被推斷爲有單位的返回類型現在