你好。类中有一些递归函数的代码union
,NonEmpty
将两个二叉搜索树合二为一。如果有人不难详细解释(最好是用例子)它是如何工作的,那就太好了。为了更好地理解,我将添加一个类,其中有一个我感兴趣的函数。
abstract class TweetSet {
def union(that: TweetSet): TweetSet
def incl(tweet: Tweet): TweetSet
}
class Empty extends TweetSet {
override def union(that: TweetSet): TweetSet = that
def incl(tweet: Tweet): TweetSet = new NonEmpty(tweet, new Empty, new Empty)
}
class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
override def union(that: TweetSet): TweetSet =
(left union (right union that)).incl(elem)
def incl(x: Tweet): TweetSet = {
if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
else this
}
}