1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Binary Tree data-structure
16 # A binary tree is a tree data structure in which each node has at most two children
17 # (referred to as the left child and the right child).
18 # In a binary tree, the degree of each node can be at most two.
19 # Binary trees are used to implement binary search trees and binary heaps,
20 # and are used for efficient searching and sorting.
29 # * node.left.key < node.key
30 # * node.right.key > node.key
31 # * no duplicates allowed
34 # * search average O(lg n) worst O(n)
35 # * insert average O(lg n) worst O(n)
36 # * delete average O(lg n) worst O(n)
39 # var tree = new BinTreeMap[Int, String]
41 # assert tree.min == "n1"
42 class BinTreeMap[K
: Comparable, E
]
45 redef type N
: BinTreeNode[K
, E
]
48 private var first_node
: nullable BinTreeNode[K
, E
] = null
49 private var last_node
: nullable BinTreeNode[K
, E
] = null
51 # O(n) in worst case, average is O(h) with h: tree height
53 # var tree = new BinTreeMap[Int, String]
54 # assert tree.is_empty
56 # assert not tree.is_empty
57 redef fun is_empty
do return root
== null
59 # O(n) in worst case, average is O(h) with h: tree height
61 # var tree = new BinTreeMap[Int, String]
62 # assert not tree.has_key(1)
63 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
64 # assert not tree.has_key(0)
65 # assert tree.has_key(2)
66 # assert not tree.has_key(6)
67 redef fun has_key
(key
) do
68 if is_empty
then return false
69 var res
= search_down
(root
.as(not null), key
)
77 private var cache_node
: nullable N
= null
79 # Get the node value associated to `key`
80 # O(n) in worst case, average is O(h) with h: tree height
82 # var tree = new BinTreeMap[Int, String]
83 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
84 # assert tree.has_key(1)
85 # assert tree[1] == "n1"
86 # assert tree.has_key(1)
87 # assert tree[2] == "n2"
89 assert not_empty
: not is_empty
90 if cache_node
!= null and cache_node
.key
== key
then return cache_node
.value
91 var res
= search_down
(root
.as(not null), key
)
92 assert has_key
: res
!= null
96 # Search `key` in `from` and its children nodes.
97 protected fun search_down
(from
: N
, key
: nullable Object): nullable N
do
98 if not key
isa Comparable then return null
99 var cmp
= key
<=> from
.key
100 if cmp
== 0 then return from
101 if from
.left
!= null and cmp
< 0 then
102 return search_down
(from
.left
.as(not null), key
)
103 else if from
.right
!= null then
104 return search_down
(from
.right
.as(not null), key
)
109 # Get the node with the minimum key
110 # O(n) in worst case, average is O(h) with h: tree height
112 # var tree = new BinTreeMap[Int, String]
113 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
114 # assert tree.min == "n1"
116 assert not_empty
: root
!= null
117 return min_from
(root
.as(not null)).value
120 # Get the left-most child from `node`.
121 protected fun min_from
(node
: N
): N
do
122 if node
.left
== null then return node
123 return min_from
(node
.left
.as(not null))
126 # Get the node with the maximum key
127 # O(n) in worst case, average is O(h) with h: tree height
129 # var tree = new BinTreeMap[Int, String]
130 # for i in [4, 2, 1, 5, 3, 6, 7, 8] do tree[i] = "n{i}"
131 # assert tree.max == "n8"
133 assert not_empty
: root
!= null
134 return max_from
(root
.as(not null)).value
137 # Get the right-most child from `node`.
138 protected fun max_from
(node
: N
): N
do
139 if node
.right
== null then return node
140 return max_from
(node
.right
.as(not null))
143 # Insert a new node in tree using `key` and `item`
144 # O(n) in worst case, average is O(h) with h: tree height
146 # var tree = new BinTreeMap[Int, String]
148 # assert tree.max == "n1"
150 # assert tree.max == "n3"
151 redef fun []=(key
, item
) do
152 insert_node
(new BinTreeNode[K
, E
](key
, item
))
155 # Add `node` in the tree.
156 protected fun insert_node
(node
: N
) do
161 shift_down
(root
.as(not null), node
)
163 if first_node
== null then
166 if last_node
!= null then
167 last_node
.next
= node
168 node
.prev
= last_node
173 # Push down the `node` in tree from a specified `from` index
174 protected fun shift_down
(from
, node
: N
) do
175 var cmp
= node
.key
<=> from
.key
177 if from
.left
== null then
181 shift_down
(from
.left
.as(not null), node
)
184 if from
.right
== null then
188 shift_down
(from
.right
.as(not null), node
)
193 # Delete node at `key` (also return the deleted node value)
194 # O(n) in worst case, average is O(h) with h: tree height
196 # var tree = new BinTreeMap[Int, String]
198 # assert tree.max == "n1"
200 # assert tree.max == "n3"
202 # assert tree.max == "n1"
203 fun delete
(key
: K
): nullable E
do
204 assert is_empty
: root
!= null
206 var node
= search_down
(root
.as(not null), key
)
207 if node
== null then return null
208 if node
.left
== null then
209 transplant
(node
, node
.right
)
210 else if node
.right
== null then
211 transplant
(node
, node
.left
)
213 var min
= min_from
(node
.right
.as(not null))
214 if min
.parent
!= node
then
215 transplant
(min
, min
.right
)
216 min
.right
= node
.right
217 min
.right
.parent
= min
219 transplant
(node
, min
)
221 min
.left
.parent
= min
223 if first_node
== node
then
226 if last_node
== node
then
227 last_node
= node
.prev
228 last_node
.next
= null
230 node
.prev
.next
= node
.next
231 node
.next
.prev
= node
.prev
236 # Swap a `node` with the `other` in this Tree
237 # note: Nodes parents are updated, children still untouched
238 protected fun transplant
(node
, other
: nullable N
) do
239 if node
== null then return
240 if node
.parent
== null then
242 else if node
== node
.parent
.left
then
243 node
.parent
.left
= other
245 node
.parent
.right
= other
247 if other
!= null then other
.parent
= node
.parent
250 # Perform left rotation on `node`
260 protected fun rotate_left
(node
: N
) do
263 if y
.left
!= null then
266 y
.parent
= node
.parent
267 if node
.parent
== null then
269 else if node
== node
.parent
.left
then
272 node
.parent
.right
= y
278 # Perform right rotation on `node`
288 protected fun rotate_right
(node
: N
) do
291 if y
.right
!= null then
292 y
.right
.parent
= node
294 y
.parent
= node
.parent
295 if node
.parent
== null then
297 else if node
== node
.parent
.right
then
298 node
.parent
.right
= y
306 # Sort the tree into an array
309 # var tree = new BinTreeMap[Int, String]
310 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
311 # assert tree.sort == ["n1", "n2", "n3", "n4", "n5"]
312 fun sort
: Array[E
] do
313 var sorted
= new Array[E
]
314 if root
== null then return sorted
315 sort_down
(root
.as(not null), sorted
)
319 # Sort the tree from `node` and place results in `sorted`.
320 protected fun sort_down
(node
: N
, sorted
: Array[E
]) do
321 if node
.left
!= null then sort_down
(node
.left
.as(not null), sorted
)
322 sorted
.add
(node
.value
)
323 if node
.right
!= null then sort_down
(node
.right
.as(not null), sorted
)
328 if root
== null then return "[]"
329 return "[{print_tree(root)}]"
332 # Print the tree starting from `node`.
333 protected fun print_tree
(node
: N
): String do
334 var s
= new FlatBuffer
336 if node
.left
!= null then s
.append
(print_tree
(node
.left
.as(not null)))
337 if node
.right
!= null then s
.append
(print_tree
(node
.right
.as(not null)))
341 redef fun show_dot
do
342 assert not_empty
: root
!= null
343 var f
= new ProcessWriter("dot", "-Txlib")
344 f
.write
"digraph \{\n"
345 dot_down
(root
.as(not null), f
)
350 # Translate the tree in dot format starting from `node`.
351 protected fun dot_down
(node
: N
, f
: ProcessWriter) do
352 if node
.left
!= null then dot_down
(node
.left
.as(not null), f
)
354 if node
.right
!= null then dot_down
(node
.right
.as(not null), f
)
359 # var tree = new BinTreeMap[Int, String]
360 # assert tree.length == 0
361 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
362 # assert tree.length == 5
363 redef fun length
do return len
365 # Nodes are iterated in the same order in which they were added to the tree.
368 # var tree = new BinTreeMap[Int, String]
369 # for i in [4, 2, 1, 5, 3] do tree[i] = "n{i}"
370 # var keys = new Array[Int]
371 # for k, v in tree do
374 # assert keys == [4, 2, 1, 5, 3]
375 redef fun iterator
do return new BinTreeMapIterator[K
, E
](self)
378 # TreeNode used by BinTree
379 class BinTreeNode[K
: Comparable, E
]
382 private var prev
: nullable BinTreeNode[K
, E
] = null
383 private var next
: nullable BinTreeNode[K
, E
] = null
385 redef type N
: BinTreeNode[K
, E
]
387 private var left_node
: nullable N
= null
389 # `left` tree node child (null if node has no left child)
390 fun left
: nullable N
do return left_node
392 # set `left` child for this node (or null if left no child)
393 # ENSURE: node.key < key (only if node != null)
394 fun left
=(node
: nullable N
) do
395 #assert node != null implies node.key < key
399 private var right_node
: nullable N
= null
401 # `right` tree node child (null if node has no right child)
402 fun right
: nullable N
do return right_node
404 # set `right` child for this node (or null if right no child)
405 # ENSURE: node.key < key (only if node != null)
406 fun right
=(node
: nullable N
) do
407 #assert node != null implies node.key > key
411 # `parent` of the `parent` of this node (null if root)
412 fun grandparent
: nullable N
do
413 if parent
== null then
420 # Other child of the `grandparent`
421 # `left` or `right` depends on the position of the current node against its parent
422 fun uncle
: nullable N
do
427 if parent
== g
.left
then
435 # Other child of the parent
436 # `left` or `right` depends on the position of the current node against its parent
437 fun sibling
: nullable N
do
438 if parent
== null then
440 else if self == parent
.left
then
442 else if self == parent
.right
then
449 redef fun to_s
do return "\{{key}: {value or else ""}\}"
452 private class BinTreeMapIterator[K
: Comparable, E
]
453 super MapIterator[K
, E
]
455 var tree
: BinTreeMap[K
, E
]
456 var current
: nullable BinTreeNode[K
, E
] = null
458 init do current
= tree
.first_node
460 redef fun is_ok
do return not current
== null
461 redef fun next
do current
= current
.next
462 redef fun item
do return current
.value
463 redef fun key
do do return current
.key