dsa_rust/hierarchies/avl_tree.rs
1/*! A safe, arena-backed (indexed) AVL tree
2
3# About
4Adelson-Velsky and Landis (AVL) trees represent theoretically optimal balanced binary search trees. AVL trees guarantee _~1.44 * log(n)_ height, and provide _O(log(n))_ search, insert, and delete operations. Red-black trees tend to be more popular even though they only guarantee _<= 2 * log(n)_ height. The imperfect height is offset by the fact that red-black trees often require fewer rotations, and the average number of rebalance operations is fewer than with AVL trees.
5
6# Design
7The design uses a flat, [Vec]-backed structure with iterative (read non-recursive) navigation. This arena-allocated design provides robust, performant operations while keeping runtime checks to a minimum. The goal of this approach is to avoid unnecessary overhead with recursive operations and extra heap allocations, making it suitable for low-spec environments.
8
9The structure trades spatial efficiency for _O(1)_ insert operations. All "pointers" represent absolute positions (as indexes) and cannot be re-calculated in less than _O(n)_ time. Thus, `remove(key)` operations do not actually shrink the physical size of the structure, leaving a `None` "hole" in the removed node's place. The structure can only grow.
10
11Due to common usage when implementing sorted map and set structures, this implementation does not accept duplicate entries by default. The structure contains an internal `SearchResult` enum that allows for duplicates by way of `Ordering::Equal`, but it is yet implemented in this version.
12
13# Example
14```rust
15 use dsa_rust::hierarchies::avl_tree::AVLTree;
16
17 let mut tree: AVLTree<u8> = AVLTree::new();
18
19 // Create the following AVL tree
20 //
21 // 39
22 // / \
23 // 17 41
24 // / \ \
25 // 13 23 43
26 // / / \
27 // 8 19 31
28 //
29 let v = [31, 13, 23, 39, 41, 43, 8, 17, 19];
30 for e in v.iter() {
31 tree.insert(*e);
32 }
33 assert_eq!(tree.get_root(), Some(&39)); // Prove that its properly rooted
34
35
36 // Remove 41 which results in the following restructure
37 //
38 // 17
39 // / \
40 // 13 39
41 // / / \
42 // 8 23 43
43 // / \
44 // 19 31
45 //
46 assert!(tree.contains(&41)); // Prove that its here today
47 let removed = tree.remove(&41).unwrap();
48 assert_eq!(removed, 41);
49 assert!(!tree.contains(&41)); // ...and gone tomorrow
50
51 tree.insert(34);
52 tree.insert(67);
53 tree.insert(2);
54 tree.insert(4);
55 tree.insert(5);
56 tree.insert(1);
57
58 // The tree is still intact, and its root has shifted
59 assert_eq!(tree.get_root().unwrap(), &31);
60
61 // In-order "snapshot" iterator
62 let mut sorted = Vec::new();
63 for e in tree.iter() {
64 sorted.push(*e)
65 }
66 assert_eq!(sorted, [1, 2, 4, 5, 8, 13, 17, 19, 23, 31, 34, 39, 43, 67]);
67```
68*/
69
70#![allow(dead_code)] // While we cook
71
72//use std::mem;
73
74use std::borrow::Borrow;
75use std::cmp::{max, Ordering};
76
77// Custom sum type for search algorithm
78enum SearchResult {
79 // The tree is empty (and uninitialized)
80 None,
81 // Index of a found key
82 Exists(usize),
83 // Index for insertion of a new key
84 Parent(usize),
85 //Parent { index: usize, side: Side },
86}
87
88#[derive(PartialEq)]
89enum Side {
90 Left,
91 Right,
92}
93// NOTE: Implementing Not provides the ability to use the
94// logical negation operator !. Implementing a custom
95// opposite() does the same thing, but more explicitly.
96// The choice to implement Not for &Side instead of Side
97// allows the re-use of Side without making it Copy/Clone.
98// Example:
99// let subtree = self.arena[child_idx].child(!side);
100// let subtree = self.arena[child_idx].child(opposite(side));
101impl<'a> std::ops::Not for &'a Side {
102 type Output = &'a Side;
103 fn not(self) -> &'a Side {
104 match self {
105 Side::Left => &Side::Right,
106 Side::Right => &Side::Left,
107 }
108 }
109}
110//impl std::ops::Not for Side {
111// type Output = Side;
112// fn not(self) -> Side {
113// match self {
114// Side::Left => Side::Right,
115// Side::Right => Side::Left,
116// }
117// }
118//}
119fn opposite(side: &Side) -> &Side {
120 match side {
121 Side::Left => &Side::Right,
122 Side::Right => &Side::Left,
123 }
124}
125
126//pub trait Keyed {
127// type Key: Ord + ?Sized;
128// fn key(&self) -> &Self::Key;
129//}
130
131#[derive(Debug)]
132pub struct AVLNode<T> {
133 value: Option<T>, // Option allows take() operations for efficient node removals
134 parent: Option<usize>, // None indicates the root of the tree
135 left: Option<usize>,
136 right: Option<usize>,
137 height: usize,
138
139 // Self-referencial position value for testing/debug ops to check algorithmic correctness
140 // TODO: remove in final implementation
141 index: usize,
142}
143impl<T> AVLNode<T> {
144 // Creates a new node with its current index, a value, and its parent (if Some).
145 // Guarantees that all nodes have a value.
146 // All initial inserts are leafs before restructuring, so left and right are set to None.
147 fn new(index: usize, value: T, parent: Option<usize>, height: usize) -> Self {
148 AVLNode {
149 index,
150 value: Some(value),
151 parent,
152 left: None,
153 right: None,
154 height,
155 }
156 }
157
158 // /// Gets the parent index of the node, if Some; None represents the tree's root
159 // fn get_parent(&self) -> Option<usize> {
160 // self.parent
161 // }
162
163 // /// Returns a tuple of the node's children
164 // fn get_children(&self) -> (Option<usize>, Option<usize>) {
165 // (self.left, self.right)
166 // }
167
168 // Returns a reference to the node's value, if Some
169 fn get_value(&self) -> Option<&T> {
170 self.value.as_ref()
171 //match &self.value {
172 // Some(val) => Some(val),
173 // None => None
174 //}
175 }
176
177 //fn is_leaf(&self) -> bool {
178 // self.left.is_none() && self.right.is_none()
179 //}
180
181 /// Get child index for a given side
182 fn child(&self, side: &Side) -> Option<usize> {
183 match side {
184 Side::Left => self.left,
185 Side::Right => self.right,
186 }
187 }
188
189 /// Set child index for a given side
190 fn set_child(&mut self, side: &Side, idx: Option<usize>) {
191 match side {
192 Side::Left => self.left = idx,
193 Side::Right => self.right = idx,
194 }
195 }
196}
197
198/// # About
199///
200/// See the [module-level documentation](crate::hierarchies::avl_tree) for more information.
201#[derive(Debug)]
202pub struct AVLTree<T> {
203 // Option wrapper for efficient take() operations during removal
204 // without incurring the wrath of O(n) resize ops
205 pub arena: Vec<Option<AVLNode<T>>>,
206 // Wont always be 0, and wont always be Some!
207 root: Option<usize>,
208}
209// Im just here to make Clippy happy
210impl<T> Default for AVLTree<T>
211where
212 //T: Keyed + Ord,
213 T: Ord,
214{
215 fn default() -> Self {
216 Self::new()
217 }
218}
219impl<T> AVLTree<T>
220where
221 //T: Keyed + Ord,
222 T: Ord,
223{
224 /// Creates a new, empty binary search tree.
225 pub fn new() -> Self {
226 AVLTree {
227 arena: Vec::new(),
228 root: None,
229 }
230 }
231
232 /// Creates a new, empty binary search tree with a given (growable) initial capacity.
233 pub fn new_with_capacity(size: usize) -> Self {
234 AVLTree {
235 arena: Vec::with_capacity(size),
236 root: Some(0),
237 }
238 }
239
240 /// Immutable node accessor
241 fn node(&self, index: usize) -> &AVLNode<T> {
242 self.arena[index]
243 .as_ref()
244 .expect("Error: Invalid immutable node access")
245 }
246
247 /// Mutable node accessor
248 fn node_mut(&mut self, index: usize) -> &mut AVLNode<T> {
249 self.arena[index]
250 .as_mut()
251 .expect("Error: Invalid mutable node access")
252 }
253
254 /// Gets a reference to the value of a key, if Some.
255 //pub fn get_node(&self, key: &T) -> Option<&T> {
256 // if let SearchResult::Exists(index) = self.search(key) {
257 // self.node(index).get_value()
258 // } else {
259 // None
260 // }
261 //}
262 //pub fn get_node(&self, key: &T) -> Option<&T> {
263 // match self.search(key) {
264 // SearchResult::Exists(index) => Some(self.node(index).get_value()?),
265 // _ => None,
266 // }
267 //}
268 pub fn get_node<Q>(&self, key: &Q) -> Option<&T>
269 where
270 Q: Ord + ?Sized,
271 //T::Key: std::borrow::Borrow<Q>,
272 T: Borrow<Q>,
273 {
274 match self.search(key) {
275 SearchResult::Exists(index) => self.node(index).get_value(),
276 _ => None,
277 }
278 }
279
280 //fn get_root_index(&self) -> Option<usize> {
281 // self.root
282 //}
283
284 pub fn get_root(&self) -> Option<&T> {
285 if let Some(node) = self.root {
286 self.node(node).get_value()
287 } else {
288 None
289 }
290 }
291
292 /// Returns a `SearchResult` enum with the following variants:
293 /// - None: Indicates an empty tree
294 /// - Parent: The key is not in the tree, but can be inserted at the parent index value
295 /// - Exists: The key was found in the tree; The caller can decide how to use this index
296 /// to deal with multi-maps and sets
297 ///
298 /// SAFETY: May panic if a node does not contain a value, but that
299 /// would violate the AVL tree invariant, so its highly unlikely, and only present to
300 /// handle the possibility of corrupted structures.
301 // Original impl: WORKS for T
302 //fn search(&self, key: &T) -> SearchResult
303 //where
304 // T: Ord,
305 //{
306 // // Early return for empty structures
307 // if self.arena.is_empty() {
308 // return SearchResult::None;
309 // };
310 //
311 // // Sets the starting point for the search
312 // // Safety: Valueless nodes violate the AVL tree invariant
313 // let mut current = self
314 // .root
315 // .expect("Error: Root should always contain a value");
316 //
317 // // Uses iterative loop instead of recursive search
318 // // because fuck stack overflows (and recursion)
319 // loop {
320 // if let Some(val) = &self.arena[current] {
321 // // Safety: Valueless nodes violate the AVL tree invariant
322 // let value = val
323 // .get_value()
324 // .expect("Error: Node does not contain a value");
325 //
326 // match value.cmp(key) {
327 // // Go right or return parent
328 // Ordering::Less => {
329 // if let Some(right) = val.right {
330 // current = right;
331 // } else {
332 // return SearchResult::Parent(current);
333 // }
334 // }
335 // // Go left or return parent
336 // Ordering::Greater => {
337 // if let Some(left) = val.left {
338 // current = left;
339 // } else {
340 // return SearchResult::Parent(current);
341 // }
342 // }
343 // // The key already exists in the tree at the current index
344 // Ordering::Equal => return SearchResult::Exists(current),
345 // }
346 // };
347 // }
348 //}
349 // Updated impl for T: Keyed
350 fn search<Q>(&self, key: &Q) -> SearchResult
351 where
352 Q: Ord + ?Sized,
353 T: Borrow<Q>,
354 {
355 // Early return for empty structures
356 if self.arena.is_empty() {
357 return SearchResult::None;
358 };
359
360 // Sets the starting point for the search
361 // Safety: Valueless nodes violate the AVL tree invariant
362 let mut current = self
363 .root
364 .expect("Error: Root should always contain a value");
365
366 // Uses iterative loop instead of recursive search
367 // because fuck stack overflows (and recursion)
368 loop {
369 if let Some(val) = &self.arena[current] {
370 // Converts &AVLNode<T> to &T
371 // Safety: Valueless nodes violate the AVL tree invariant
372 let value = val
373 .get_value()
374 .expect("Error: Node does not contain a value");
375
376 let value_key: &Q = value.borrow();
377
378 match value_key.cmp(key) {
379 // Go right or return parent
380 Ordering::Less => {
381 if let Some(right) = val.right {
382 current = right;
383 } else {
384 return SearchResult::Parent(current);
385 }
386 }
387 // Go left or return parent
388 Ordering::Greater => {
389 if let Some(left) = val.left {
390 current = left;
391 } else {
392 return SearchResult::Parent(current);
393 }
394 }
395 // The key already exists in the tree at the current index
396 Ordering::Equal => return SearchResult::Exists(current),
397 }
398 };
399 }
400 }
401 //fn search<Q>(&self, key: &Q) -> SearchResult
402 //where
403 // Q: Ord + ?Sized,
404 // //T::Key: Borrow<Q>,
405 // T: Borrow<Q>,
406 //{
407 // if self.arena.is_empty() {
408 // return SearchResult::None;
409 // }
410 //
411 // let mut current = self.root.expect("root should exist");
412 //
413 // loop {
414 // let node_ref = self.arena[current]
415 // .as_ref()
416 // .expect("missing node in arena");
417 // let value = node_ref
418 // .value
419 // .as_ref()
420 // .expect("node missing value");
421 //
422 // let node_key = value.key();
423 //
424 // match key.cmp(node_key.borrow()) {
425 // Ordering::Less => {
426 // if let Some(left) = node_ref.left {
427 // current = left;
428 // } else {
429 // return SearchResult::Parent(current);
430 // }
431 // }
432 // Ordering::Greater => {
433 // if let Some(right) = node_ref.right {
434 // current = right;
435 // } else {
436 // return SearchResult::Parent(current);
437 // }
438 // }
439 // Ordering::Equal => return SearchResult::Exists(current),
440 // }
441 // }
442 //}
443
444 /// Returns true if the key exists in the tree.
445 //pub fn contains(&self, key: &T) -> bool {
446 // match self.search(key) {
447 // SearchResult::Exists(_) => true,
448 // _ => false,
449 // }
450 //}
451 //pub fn contains(&self, key: &T) -> bool {
452 // matches!(self.search(key), SearchResult::Exists(_))
453 //}
454 pub fn contains<Q>(&self, key: &Q) -> bool
455 where
456 Q: Ord + ?Sized,
457 //T::Key: Borrow<Q>,
458 T: Borrow<Q>,
459 {
460 matches!(self.search(key), SearchResult::Exists(_))
461 }
462
463 /// Inserts the given key into the tree maintaining an AVL structure.
464 ///
465 /// NOTE: Does not handle duplicate keys by convention, but may overwrite values for
466 /// arbitrarily complex T with custom Ordering.
467 //pub fn insert(&mut self, key: T) {
468 // match self.search(&key) {
469 pub fn insert(&mut self, key: T)
470 where
471 //T: Keyed + Ord,
472 T: Ord,
473 {
474 // Pass &T::Key to search; search itself is generic over Q
475 //match self.search(key.key()) {
476 match self.search(&key) {
477 SearchResult::Parent(parent) => {
478 // Determine child position
479 let new_idx = self.arena.len();
480 // SAFETY: Parent is guaranteed by search() enums
481 //if let Some(val) = &self.arena[parent].as_mut().unwrap().value {
482 if let Some(val) = &self.node_mut(parent).value {
483 match key.cmp(val) {
484 Ordering::Less => {
485 //self.arena[parent].as_mut().unwrap().left = Some(new_idx);
486 self.node_mut(parent).left = Some(new_idx);
487 }
488 Ordering::Greater => {
489 //self.arena[parent].as_mut().unwrap().right = Some(new_idx);
490 self.node_mut(parent).right = Some(new_idx);
491 }
492 Ordering::Equal => {}
493 }
494 };
495
496 // Insert new node
497 self.arena
498 .push(Some(AVLNode::new(new_idx, key, Some(parent), 1)));
499
500 // Walk up the tree to update heights and rebalance
501 let mut current = Some(parent);
502 while let Some(idx) = current {
503 self.update_node_height(idx);
504 self.restructure(idx);
505 //current = self.arena[idx].as_mut().unwrap().parent;
506 current = self.node_mut(idx).parent;
507 }
508 }
509 SearchResult::None => {
510 // Empty tree, insert root
511 let new_node = AVLNode::new(0, key, None, 1);
512 self.arena.push(Some(new_node));
513 self.root = Some(0);
514 }
515 SearchResult::Exists(_) => {}
516 }
517 }
518
519 /// Removes and returns an element from the AVL tree as an owned value.
520 //pub fn remove(&mut self, key: &T) -> Option<T> {
521 // let target_index = match self.search(key) {
522 //pub fn remove(&mut self, key: &T) -> Option<T>
523 //where
524 // //T: Keyed + Ord,
525 // T: Ord,
526 //{
527 pub fn remove<Q>(&mut self, key: &Q) -> Option<T>
528 where
529 Q: Ord + ?Sized,
530 T: Borrow<Q>,
531 {
532 //let target_index = match self.search(key.key()) {
533 let target_index = match self.search(key) {
534 SearchResult::Exists(idx) => idx,
535 _ => return None,
536 };
537
538 // Step 1: Find node to physically remove (node with ≤1 child)
539 let mut remove_index = target_index;
540 if self.node(remove_index).left.is_some() && self.node(remove_index).right.is_some() {
541 // Node has two children: find in-order successor
542 let mut succ_index = self.node(remove_index).right.unwrap();
543 while let Some(left) = self.node(succ_index).left {
544 succ_index = left;
545 }
546
547 // Move successor's value into target node
548 //let succ_value = self.arena[succ_index].take().unwrap().value;
549 //self.node_mut(remove_index).value = succ_value;
550
551 // 1. Take the value out of the successor node.
552 let succ_value = self.node_mut(succ_index).value.take();
553
554 // 2. Replace the target's value with the successor's,
555 // getting the original target value back.
556 let original_value = self
557 .node_mut(target_index)
558 .value
559 .replace(succ_value.unwrap());
560
561 // 3. Place the original target value into the successor node,
562 // which we are about to remove.
563 self.node_mut(succ_index).value = original_value;
564
565 // Now, the successor node can be safely removed, and it
566 // contains the correct value to return.
567
568 // Now remove the successor node (guaranteed ≤1 child)
569 remove_index = succ_index;
570 }
571
572 // Step 2: Identify the child of the node to remove (if any)
573 let child_index = self
574 .node(remove_index)
575 .left
576 .or(self.node(remove_index).right);
577
578 // Step 3: Update parent to point to the child
579 let parent_index = self.node(remove_index).parent;
580 if let Some(p_idx) = parent_index {
581 let parent = self.node_mut(p_idx);
582 if parent.left == Some(remove_index) {
583 parent.left = child_index;
584 } else {
585 parent.right = child_index;
586 }
587 } else {
588 // Removing root
589 self.root = child_index;
590 }
591
592 // Step 4: Update child's parent
593 if let Some(c_idx) = child_index {
594 self.node_mut(c_idx).parent = parent_index;
595 }
596
597 // Step 5: Take the node for return
598 let removed_value = self.arena[remove_index].take().map(|n| n.value);
599
600 // Step 6: Walk up ancestors to update heights and rebalance
601 let mut current = parent_index;
602 while let Some(idx) = current {
603 self.update_node_height(idx);
604 self.restructure(idx);
605 current = self.node(idx).parent;
606 }
607
608 removed_value?
609 }
610
611 // Utility functions
612 ////////////////////
613
614 /// Updates the height of an arbitrary node in an AVL tree
615 /// where leaf nodes are defined as having height 1
616 //fn update_node_height(&mut self, index: usize) {
617 // let left = self.arena[index].as_mut().unwrap().left.map_or(0, |idx| self.arena[idx].as_mut().unwrap().height);
618 // let right = self.arena[index].as_mut().unwrap().right.map_or(0, |idx| self.arena[idx].as_mut().unwrap().height);
619 // // Works for internal and leaf nodes, because max(0, 0) + 1 = 1
620 // self.arena[index].as_mut().unwrap().height = max(left, right) + 1
621 //}
622 fn update_node_height(&mut self, index: usize) {
623 let left = self
624 .node_mut(index)
625 .left
626 .map_or(0, |idx| self.node_mut(idx).height);
627 let right = self
628 .node_mut(index)
629 .right
630 .map_or(0, |idx| self.node_mut(idx).height);
631 // Works for internal and leaf nodes, because max(0, 0) + 1 = 1
632 self.node_mut(index).height = max(left, right) + 1
633 }
634
635 /// Rotate the subtree rooted at `root_idx` in the given direction.
636 /// `side` is the direction of the original heavy side (Side::Left or Side::Right).
637 fn rotate(&mut self, root_idx: usize, side: &Side) {
638 // Heavy child becomes the new root of the subtree
639 let child_idx = self
640 .node_mut(root_idx)
641 .child(side)
642 .expect("Rotation requires heavy child");
643
644 // Move child's opposite subtree into root's heavy side
645 //let subtree = self.arena[child_idx].child(opposite(side));
646 let subtree = self.node_mut(child_idx).child(!side);
647 self.node_mut(root_idx).set_child(side, subtree);
648 if let Some(sub_idx) = subtree {
649 self.node_mut(sub_idx).parent = Some(root_idx);
650 }
651
652 // Update parent pointers
653 let parent_idx = self.node_mut(root_idx).parent;
654 self.node_mut(child_idx).parent = parent_idx;
655
656 if let Some(p_idx) = parent_idx {
657 if self.node_mut(p_idx).left == Some(root_idx) {
658 self.node_mut(p_idx).left = Some(child_idx);
659 } else {
660 self.node_mut(p_idx).right = Some(child_idx);
661 }
662 } else {
663 self.root = Some(child_idx);
664 }
665
666 // Make old root the child of new root
667 self.node_mut(child_idx)
668 .set_child(opposite(side), Some(root_idx));
669 self.node_mut(root_idx).parent = Some(child_idx);
670
671 // Update heights
672 self.update_node_height(root_idx);
673 self.update_node_height(child_idx);
674 }
675
676 /// Determines left-heavy (>0) or right-heavy (<0) balance factors for a given node index
677 /// The necessity for restructure operations can be determined agnostically by
678 /// `abs(balance_factor(index)) >= 2`
679 fn balance_factor(&self, index: usize) -> isize {
680 let node = &self.node(index);
681 let left = node.left.map_or(0, |l| self.node(l).height as isize);
682 let right = node.right.map_or(0, |r| self.node(r).height as isize);
683 left - right
684 }
685
686 /// Rebalances the subtree rooted at `index`.
687 /// Performs single or double rotations as necessary.
688 fn restructure(&mut self, index: usize) {
689 // Not all inserts require restructuring
690 let balance = self.balance_factor(index);
691 if balance.abs() < 2 {
692 return;
693 }
694
695 // Determine heavy side
696 let heavy_side = if balance > 1 { Side::Left } else { Side::Right };
697
698 // Determine the child index for the heavy side
699 let child_idx = match self.node(index).child(&heavy_side) {
700 Some(idx) => idx,
701 // SAFETY: A None value on the child violates the AVL invariant
702 None => panic!("Error: Heavy child is None"),
703 };
704
705 // Double rotation check
706 //let child_balance = self.balance_factor(child_idx);
707 //if heavy_side == Side::Left && child_balance < 0 {
708 // self.rotate(child_idx, &Side::Right);
709 //} else if heavy_side == Side::Right && child_balance > 0 {
710 // self.rotate(child_idx, &Side::Left);
711 //}
712 match (&heavy_side, self.balance_factor(child_idx)) {
713 (Side::Left, b) if b < 0 => self.rotate(child_idx, &Side::Right), // LR
714 (Side::Right, b) if b > 0 => self.rotate(child_idx, &Side::Left), // RL
715 _ => {}
716 }
717
718 // Single rotation on parent
719 self.rotate(index, &heavy_side);
720 }
721
722 /// Produces a "snapshot" iterator over immutable references to the
723 /// tree in its current state.
724 pub fn iter(&self) -> InOrderIter<'_, T> {
725 InOrderIter::new(&self.arena, self.root)
726 }
727}
728
729pub struct InOrderIter<'a, T> {
730 arena: &'a [Option<AVLNode<T>>],
731 stack: Vec<usize>, // store indices, not references
732 current: Option<usize>,
733}
734impl<'a, T> InOrderIter<'a, T> {
735 fn new(arena: &'a [Option<AVLNode<T>>], root: Option<usize>) -> Self {
736 Self {
737 arena,
738 stack: Vec::new(),
739 current: root,
740 }
741 }
742}
743impl<'a, T> Iterator for InOrderIter<'a, T> {
744 type Item = &'a T;
745
746 fn next(&mut self) -> Option<Self::Item> {
747 while let Some(idx) = self.current {
748 if let Some(node) = self.arena[idx].as_ref() {
749 self.stack.push(idx);
750 self.current = node.left;
751 continue;
752 } else {
753 // Node was removed, skip
754 self.current = None;
755 }
756 }
757
758 if let Some(idx) = self.stack.pop() {
759 if let Some(node) = self.arena[idx].as_ref() {
760 self.current = node.right;
761 node.value.as_ref()
762 } else {
763 // Skip removed node
764 self.next()
765 }
766 } else {
767 None
768 }
769 }
770}
771
772#[test]
773fn avl_construction() {
774 let mut tree: AVLTree<u8> = AVLTree::new();
775
776 let v = [31, 13, 23, 39, 41, 43, 8, 17, 19];
777 // Produces the following AVL tree
778 //
779 // 39
780 // / \
781 // 17 41
782 // / \ \
783 // 13 23 43
784 // / / \
785 // 8 19 31
786 //
787 for e in v.iter() {
788 tree.insert(*e);
789 }
790
791 // Tests that the root is being updated properly
792 assert_eq!(tree.get_root().unwrap(), &39);
793 assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(39));
794 let root_node = &tree.node(tree.root.expect("nah, brah"));
795 assert_eq!(tree.node(root_node.left.unwrap()).value, Some(17));
796 assert_eq!(tree.node(root_node.right.unwrap()).value, Some(41));
797 assert_eq!(tree.node(0).left, None);
798 assert_eq!(tree.node(0).right, None);
799
800 assert_eq!(tree.node(tree.node(7).left.unwrap()).value, Some(13));
801 assert_eq!(tree.node(tree.node(7).right.unwrap()).value, Some(23));
802
803 let mut sorted = Vec::new();
804 for e in tree.iter() {
805 sorted.push(*e)
806 }
807 assert_eq!(sorted, [8, 13, 17, 19, 23, 31, 39, 41, 43]);
808
809 let mut tree: AVLTree<u8> = AVLTree::new();
810 let v = [1, 2, 3, 4, 5, 6, 7];
811 // Produces the following AVL tree
812 //
813 // 4
814 // / \
815 // 2 6
816 // / \ / \
817 // 1 3 5 7
818 //
819 for e in v.iter() {
820 tree.insert(*e);
821 }
822
823 assert_eq!(tree.get_root().unwrap(), &4);
824 assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(4));
825 let root_node = &tree.node(tree.root.expect("nah, brah"));
826 assert_eq!(tree.node(root_node.left.unwrap()).value, Some(2));
827 assert_eq!(tree.node(root_node.right.unwrap()).value, Some(6));
828 assert_eq!(tree.node(0).left, None);
829 assert_eq!(tree.node(0).right, None);
830
831 assert_eq!(tree.node(tree.node(5).left.unwrap()).value, Some(5));
832 assert_eq!(tree.node(tree.node(5).right.unwrap()).value, Some(7));
833
834 let mut sorted = Vec::new();
835 for e in tree.iter() {
836 sorted.push(*e)
837 }
838 assert_eq!(sorted, [1, 2, 3, 4, 5, 6, 7]);
839
840 // Print visualization/debug
841 eprintln!("{tree:#?}");
842 //panic!();
843}
844
845#[test]
846fn avl_removals() {
847 let mut tree: AVLTree<u8> = AVLTree::new();
848
849 // Construct the following AVL tree
850 //
851 // 39
852 // / \
853 // 17 41
854 // / \ \
855 // 13 23 43
856 // / / \
857 // 8 19 31
858 //
859 let v = [31, 13, 23, 39, 41, 43, 8, 17, 19];
860 for e in v.iter() {
861 tree.insert(*e);
862 }
863
864 // Remove 31 which results in the following AVL tree
865 //
866 // 39
867 // / \
868 // 17 41
869 // / \ \
870 // 13 23 43
871 // / /
872 // 8 19
873 //
874 assert_eq!(tree.get_root().unwrap(), &39);
875 assert!(tree.contains(&31));
876 let removed = tree.remove(&31).unwrap();
877 assert_eq!(removed, 31);
878 assert!(!tree.contains(&31));
879
880 assert_eq!(tree.node(tree.node(2).left.expect("")).value, Some(19));
881 assert_eq!(tree.node(2).right, None);
882
883 // Remove 41 which results in the following AVL tree
884 //
885 // 17
886 // / \
887 // 13 39
888 // / / \
889 // 8 23 43
890 // /
891 // 19
892 //
893 assert!(tree.contains(&41));
894 let removed = tree.remove(&41).unwrap();
895 assert_eq!(removed, 41);
896 assert!(tree.remove(&41).is_none()); // Test that 41 was really removed
897 assert!(!tree.contains(&41));
898
899 // 39 now has L 23 and R 43
900 assert_eq!(tree.node(tree.node(3).left.expect("")).value, Some(23));
901 assert_eq!(tree.node(tree.node(3).right.expect("")).value, Some(43));
902
903 // 17 is now rooth with L 13 and R 39
904 assert_eq!(tree.get_root().unwrap(), &17);
905 assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(17));
906 assert_eq!(tree.node(tree.node(7).left.expect("")).value, Some(13));
907 assert_eq!(tree.node(tree.node(7).right.expect("")).value, Some(39));
908 // The old root 39 now has L 23 and R 43
909 assert_eq!(tree.node(tree.node(3).left.expect("")).value, Some(23));
910 assert_eq!(tree.node(tree.node(3).right.expect("")).value, Some(43));
911
912 // Remove 8 which results in the following AVL tree
913 //
914 // 23
915 // / \
916 // 17 39
917 // / \ \
918 // 13 19 43
919 //
920 assert!(tree.contains(&8));
921 let removed = tree.remove(&8).unwrap();
922 assert_eq!(removed, 8);
923 assert!(tree.remove(&8).is_none()); // Test that 8 was really removed
924 assert!(!tree.contains(&8));
925
926 // 23 is now rooth with L 17 and R 39
927 assert_eq!(tree.get_root().unwrap(), &23);
928 assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(23));
929 assert_eq!(tree.node(tree.node(2).left.expect("")).value, Some(17));
930 assert_eq!(tree.node(tree.node(2).right.expect("")).value, Some(39));
931 // The old root 17 now has L 13 and R 19
932 assert_eq!(tree.node(tree.node(7).left.expect("")).value, Some(13));
933 assert_eq!(tree.node(tree.node(7).right.expect("")).value, Some(19));
934
935 // Print visualization/debug
936 eprintln!("{tree:#?}");
937 //panic!();
938}