summaryrefslogtreecommitdiff
path: root/src/library/scala/collection/mutable/AVLTree.scala
blob: b63d0aae33ab0036096d7e34471f11380b47811d (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection
package mutable

/**
 * An immutable AVL Tree implementation formerly used by mutable.TreeSet
 *
 * @author Lucien Pereira
 */
@deprecated("AVLTree and its related classes are being removed from the standard library since they're not different enough from RedBlackTree to justify keeping them.", "2.11.2")
private[mutable] sealed trait AVLTree[+A] extends Serializable {
  def balance: Int

  def depth: Int

  def iterator[B >: A]: Iterator[B] = Iterator.empty

  def contains[B >: A](value: B, ordering: Ordering[B]): Boolean = false

  /**
   * Returns a new tree containing the given element.
   * Throws an IllegalArgumentException if element is already present.
   *
   */
  def insert[B >: A](value: B, ordering: Ordering[B]): AVLTree[B] = Node(value, Leaf, Leaf)

  /**
   * Return a new tree which not contains given element.
   *
   */
  def remove[B >: A](value: B, ordering: Ordering[B]): AVLTree[A] =
    throw new NoSuchElementException(String.valueOf(value))

  /**
   * Return a tuple containing the smallest element of the provided tree
   * and a new tree from which this element has been extracted.
   *
   */
  def removeMin[B >: A]: (B, AVLTree[B]) = sys.error("Should not happen.")

  /**
   * Return a tuple containing the biggest element of the provided tree
   * and a new tree from which this element has been extracted.
   *
   */
  def removeMax[B >: A]: (B, AVLTree[B]) = sys.error("Should not happen.")

  def rebalance[B >: A]: AVLTree[B] = this

  def leftRotation[B >: A]: Node[B] = sys.error("Should not happen.")

  def rightRotation[B >: A]: Node[B] = sys.error("Should not happen.")

  def doubleLeftRotation[B >: A]: Node[B] = sys.error("Should not happen.")

  def doubleRightRotation[B >: A]: Node[B] = sys.error("Should not happen.")
}

/**
 * @deprecated("AVLTree and its related classes are being removed from the standard library since they're not different enough from RedBlackTree to justify keeping them.", "2.11.0")
 */
private case object Leaf extends AVLTree[Nothing] {
  override val balance: Int = 0

  override val depth: Int = -1
}

/**
 * @deprecated("AVLTree and its related classes are being removed from the standard library since they're not different enough from RedBlackTree to justify keeping them.", "2.11.0")
 */
private case class Node[A](data: A, left: AVLTree[A], right: AVLTree[A]) extends AVLTree[A] {
  override val balance: Int = right.depth - left.depth

  override val depth: Int = math.max(left.depth, right.depth) + 1

  override def iterator[B >: A]: Iterator[B] = new AVLIterator(this)

  override def contains[B >: A](value: B, ordering: Ordering[B]) = {
    val ord = ordering.compare(value, data)
    if (0 == ord)
      true
    else if (ord < 0)
      left.contains(value, ordering)
    else
      right.contains(value, ordering)
  }

  /**
   * Returns a new tree containing the given element.
   * Throws an IllegalArgumentException if element is already present.
   *
   */
  override def insert[B >: A](value: B, ordering: Ordering[B]) = {
    val ord = ordering.compare(value, data)
    if (0 == ord)
      throw new IllegalArgumentException()
    else if (ord < 0)
      Node(data, left.insert(value, ordering), right).rebalance
    else
      Node(data, left, right.insert(value, ordering)).rebalance
  }

  /**
   * Return a new tree which not contains given element.
   *
   */
  override def remove[B >: A](value: B, ordering: Ordering[B]): AVLTree[A] = {
    val ord = ordering.compare(value, data)
    if(ord == 0) {
      if (Leaf == left) {
        if (Leaf == right) {
          Leaf
        } else {
          val (min, newRight) = right.removeMin
          Node(min, left, newRight).rebalance
        }
      } else {
        val (max, newLeft) = left.removeMax
        Node(max, newLeft, right).rebalance
      }
    } else if (ord < 0) {
      Node(data, left.remove(value, ordering), right).rebalance
    } else {
      Node(data, left, right.remove(value, ordering)).rebalance
    }
  }

  /**
   * Return a tuple containing the smallest element of the provided tree
   * and a new tree from which this element has been extracted.
   *
   */
  override def removeMin[B >: A]: (B, AVLTree[B]) = {
    if (Leaf == left)
      (data, right)
    else {
      val (min, newLeft) = left.removeMin
      (min, Node(data, newLeft, right).rebalance)
    }
  }

  /**
   * Return a tuple containing the biggest element of the provided tree
   * and a new tree from which this element has been extracted.
   *
   */
  override def removeMax[B >: A]: (B, AVLTree[B]) = {
    if (Leaf == right)
      (data, left)
    else {
      val (max, newRight) = right.removeMax
      (max, Node(data, left, newRight).rebalance)
    }
  }

  override def rebalance[B >: A] = {
    if (-2 == balance) {
      if (1 == left.balance)
        doubleRightRotation
      else
        rightRotation
    } else if (2 == balance) {
      if (-1 == right.balance)
        doubleLeftRotation
      else
        leftRotation
    } else {
      this
    }
  }

  override def leftRotation[B >: A] = {
    if (Leaf != right) {
      val r: Node[A] = right.asInstanceOf[Node[A]]
      Node(r.data, Node(data, left, r.left), r.right)
    } else sys.error("Should not happen.")
  }

  override def rightRotation[B >: A] = {
    if (Leaf != left) {
      val l: Node[A] = left.asInstanceOf[Node[A]]
      Node(l.data, l.left, Node(data, l.right, right))
    } else sys.error("Should not happen.")
  }

  override def doubleLeftRotation[B >: A] = {
    if (Leaf != right) {
      val r: Node[A] = right.asInstanceOf[Node[A]]
      // Let's save an instanceOf by 'inlining' the left rotation
      val rightRotated = r.rightRotation
      Node(rightRotated.data, Node(data, left, rightRotated.left), rightRotated.right)
    } else sys.error("Should not happen.")
  }

  override def doubleRightRotation[B >: A] = {
    if (Leaf != left) {
      val l: Node[A] = left.asInstanceOf[Node[A]]
      // Let's save an instanceOf by 'inlining' the right rotation
      val leftRotated = l.leftRotation
      Node(leftRotated.data, leftRotated.left, Node(data, leftRotated.right, right))
    } else sys.error("Should not happen.")
  }
}

/**
 * @deprecated("AVLTree and its related classes are being removed from the standard library since they're not different enough from RedBlackTree to justify keeping them.", "2.11.0")
 */
private class AVLIterator[A](root: Node[A]) extends Iterator[A] {
  val stack = mutable.ArrayStack[Node[A]](root)
  diveLeft()

  private def diveLeft(): Unit = {
    if (Leaf != stack.head.left) {
      val left: Node[A] = stack.head.left.asInstanceOf[Node[A]]
      stack.push(left)
      diveLeft()
    }
  }

  private def engageRight(): Unit = {
    if (Leaf != stack.head.right) {
      val right: Node[A] = stack.head.right.asInstanceOf[Node[A]]
      stack.pop()
      stack.push(right)
      diveLeft()
    } else
      stack.pop()
  }

  override def hasNext: Boolean = !stack.isEmpty

  override def next(): A = {
    if (stack.isEmpty)
      throw new NoSuchElementException()
    else {
      val result = stack.head.data
      // Let's maintain stack for the next invocation
      engageRight()
      result
    }
  }
}