blob: 86e44df684660fd2cb545c4285c4887bcf48741c (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/* NSC -- new Scala compiler
* Copyright 2005-2010 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
package scala.tools.nsc
package util
/** Sets implemented as binary trees.
*
* @author Martin Odersky
* @version 1.0
*/
class TreeSet[T >: Null <: AnyRef](less: (T, T) => Boolean) extends Set[T] {
private class Tree(val elem: T) {
var l: Tree = null
var r: Tree = null
}
private var tree: Tree = null
def findEntry(x: T): T = {
def find(t: Tree): T = {
if (t eq null) null
else if (less(x, t.elem)) find(t.l)
else if (less(t.elem, x)) find(t.r)
else t.elem
}
find(tree)
}
def addEntry(x: T) {
def add(t: Tree): Tree = {
if (t eq null) new Tree(x)
else if (less(x, t.elem)) { t.l = add(t.l); t }
else if (less(t.elem, x)) { t.r = add(t.r); t }
else t
}
tree = add(tree)
}
def iterator = {
def elems(t: Tree): Iterator[T] = {
if (t eq null) Iterator.empty
else elems(t.l) ++ (Iterator single t.elem) ++ elems(t.r)
}
elems(tree)
}
override def toString(): String = {
if (tree eq null) "<empty>" else "(..." + tree.elem + "...)"
}
}
|