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
199/// # About
200///
201/// See the [module-level documentation](crate::hierarchies::avl_tree) for more information.
202#[derive(Debug)]
203pub struct AVLTree<T> {
204    // Option wrapper for efficient take() operations during removal
205    // without incurring the wrath of O(n) resize ops
206    pub arena: Vec<Option<AVLNode<T>>>, 
207    // Wont always be 0, and wont always be Some!
208    root: Option<usize>, 
209}
210// Im just here to make Clippy happy
211impl<T> Default for AVLTree<T>
212where
213    //T: Keyed + Ord,
214    T: Ord,
215{
216    fn default() -> Self {
217        Self::new()
218    }
219}
220impl<T> AVLTree<T>
221where
222    //T: Keyed + Ord,
223    T: Ord,
224{
225    /// Creates a new, empty binary search tree.
226    pub fn new() -> Self {
227        AVLTree {
228            arena: Vec::new(),
229            root: None,
230        }
231    }
232
233    /// Creates a new, empty binary search tree with a given (growable) initial capacity.
234    pub fn new_with_capacity(size: usize) -> Self {
235        AVLTree {
236            arena: Vec::with_capacity(size),
237            root: Some(0),
238        }
239    }
240
241    /// Immutable node accessor 
242    fn node(&self, index: usize) -> &AVLNode<T> {
243        self.arena[index].as_ref().expect("Error: Invalid immutable node access")
244    }
245
246    /// Mutable node accessor
247    fn node_mut(&mut self, index: usize) -> &mut AVLNode<T> {
248        self.arena[index].as_mut().expect("Error: Invalid mutable node access")
249    }
250
251    /// Gets a reference to the value of a key, if Some.
252    //pub fn get_node(&self, key: &T) -> Option<&T> {
253    //    if let SearchResult::Exists(index) = self.search(key) {
254    //        self.node(index).get_value()
255    //    } else {
256    //        None
257    //    }
258    //}
259    //pub fn get_node(&self, key: &T) -> Option<&T> {
260    //    match self.search(key) {
261    //        SearchResult::Exists(index) => Some(self.node(index).get_value()?),
262    //        _ => None,
263    //    }
264    //}
265    pub fn get_node<Q>(&self, key: &Q) -> Option<&T>
266    where
267        Q: Ord + ?Sized,
268        //T::Key: std::borrow::Borrow<Q>,
269        T: Borrow<Q>,
270    {
271        match self.search(key) {
272            SearchResult::Exists(index) => self.node(index).get_value(),
273            _ => None,
274        }
275    }
276
277    //fn get_root_index(&self) -> Option<usize> {
278    //    self.root
279    //}
280
281    pub fn get_root(&self) -> Option<&T> {
282        if let Some(node) = self.root {
283            self.node(node).get_value()
284        } else { None }
285    }
286
287    /// Returns a `SearchResult` enum with the following variants:
288    /// - None: Indicates an empty tree
289    /// - Parent: The key is not in the tree, but can be inserted at the parent index value
290    /// - Exists: The key was found in the tree; The caller can decide how to use this index
291    ///   to deal with multi-maps and sets
292    ///
293    /// SAFETY: May panic if a node does not contain a value, but that 
294    /// would violate the AVL tree invariant, so its highly unlikely, and only present to
295    /// handle the possibility of corrupted structures.
296    // Original impl: WORKS for T
297    //fn search(&self, key: &T) -> SearchResult
298    //where
299    //    T: Ord,
300    //{
301    //    // Early return for empty structures
302    //    if self.arena.is_empty() {
303    //        return SearchResult::None;
304    //    };
305    //
306    //    // Sets the starting point for the search
307    //    // Safety: Valueless nodes violate the AVL tree invariant
308    //    let mut current = self
309    //        .root
310    //        .expect("Error: Root should always contain a value");
311    //
312    //    // Uses iterative loop instead of recursive search
313    //    // because fuck stack overflows (and recursion)
314    //    loop {
315    //        if let Some(val) = &self.arena[current] {
316    //            // Safety: Valueless nodes violate the AVL tree invariant
317    //            let value = val
318    //                .get_value()
319    //                .expect("Error: Node does not contain a value");
320    //
321    //            match value.cmp(key) {
322    //                // Go right or return parent
323    //                Ordering::Less => {
324    //                    if let Some(right) = val.right {
325    //                        current = right;
326    //                    } else {
327    //                        return SearchResult::Parent(current);
328    //                    }
329    //                }
330    //                // Go left or return parent
331    //                Ordering::Greater => {
332    //                    if let Some(left) = val.left {
333    //                        current = left;
334    //                    } else {
335    //                        return SearchResult::Parent(current);
336    //                    }
337    //                }
338    //                // The key already exists in the tree at the current index
339    //                Ordering::Equal => return SearchResult::Exists(current),
340    //            }
341    //        };
342    //    }
343    //}
344    // Updated impl for T: Keyed
345    fn search<Q>(&self, key: &Q) -> SearchResult 
346        where Q: Ord + ?Sized, T: Borrow<Q>, 
347    {
348        // Early return for empty structures
349        if self.arena.is_empty() {
350            return SearchResult::None;
351        };
352    
353        // Sets the starting point for the search
354        // Safety: Valueless nodes violate the AVL tree invariant
355        let mut current = self
356            .root
357            .expect("Error: Root should always contain a value");
358    
359        // Uses iterative loop instead of recursive search
360        // because fuck stack overflows (and recursion)
361        loop {
362            if let Some(val) = &self.arena[current] {
363                // Converts &AVLNode<T> to &T
364                // Safety: Valueless nodes violate the AVL tree invariant
365                let value = val
366                    .get_value()
367                    .expect("Error: Node does not contain a value");
368    
369                let value_key: &Q = value.borrow();
370    
371                match value_key.cmp(key) {
372                    // Go right or return parent
373                    Ordering::Less => {
374                        if let Some(right) = val.right {
375                            current = right;
376                        } else {
377                            return SearchResult::Parent(current);
378                        }
379                    }
380                    // Go left or return parent
381                    Ordering::Greater => {
382                        if let Some(left) = val.left {
383                            current = left;
384                        } else {
385                            return SearchResult::Parent(current);
386                        }
387                    }
388                    // The key already exists in the tree at the current index
389                    Ordering::Equal => return SearchResult::Exists(current),
390                }
391            };
392        }
393    }
394    //fn search<Q>(&self, key: &Q) -> SearchResult
395    //where
396    //    Q: Ord + ?Sized,
397    //    //T::Key: Borrow<Q>,
398    //    T: Borrow<Q>,
399    //{
400    //    if self.arena.is_empty() {
401    //        return SearchResult::None;
402    //    }
403    //
404    //    let mut current = self.root.expect("root should exist");
405    //
406    //    loop {
407    //        let node_ref = self.arena[current]
408    //            .as_ref()
409    //            .expect("missing node in arena");
410    //        let value = node_ref
411    //            .value
412    //            .as_ref()
413    //            .expect("node missing value");
414    //
415    //        let node_key = value.key();
416    //
417    //        match key.cmp(node_key.borrow()) {
418    //            Ordering::Less => {
419    //                if let Some(left) = node_ref.left {
420    //                    current = left;
421    //                } else {
422    //                    return SearchResult::Parent(current);
423    //                }
424    //            }
425    //            Ordering::Greater => {
426    //                if let Some(right) = node_ref.right {
427    //                    current = right;
428    //                } else {
429    //                    return SearchResult::Parent(current);
430    //                }
431    //            }
432    //            Ordering::Equal => return SearchResult::Exists(current),
433    //        }
434    //    }
435    //}
436
437    /// Returns true if the key exists in the tree.
438    //pub fn contains(&self, key: &T) -> bool {
439    //    match self.search(key) {
440    //        SearchResult::Exists(_) => true,
441    //        _ => false,
442    //    }
443    //}
444    //pub fn contains(&self, key: &T) -> bool {
445    //    matches!(self.search(key), SearchResult::Exists(_))
446    //}
447    pub fn contains<Q>(&self, key: &Q) -> bool
448    where
449        Q: Ord + ?Sized,
450        //T::Key: Borrow<Q>,
451        T: Borrow<Q>,
452    {
453        matches!(self.search(key), SearchResult::Exists(_))
454    }
455
456    /// Inserts the given key into the tree maintaining an AVL structure.
457    ///
458    /// NOTE: Does not handle duplicate keys by convention, but may overwrite values for
459    /// arbitrarily complex T with custom Ordering.
460    //pub fn insert(&mut self, key: T) {
461    //    match self.search(&key) {
462    pub fn insert(&mut self, key: T)
463    where
464        //T: Keyed + Ord,
465        T: Ord,
466    {
467        // Pass &T::Key to search; search itself is generic over Q
468        //match self.search(key.key()) {
469        match self.search(&key) {
470            SearchResult::Parent(parent) => {
471                // Determine child position
472                let new_idx = self.arena.len();
473                // SAFETY: Parent is guaranteed by search() enums
474                //if let Some(val) = &self.arena[parent].as_mut().unwrap().value {
475                if let Some(val) = &self.node_mut(parent).value {
476                    match key.cmp(val) {
477                        Ordering::Less => { 
478                            //self.arena[parent].as_mut().unwrap().left = Some(new_idx);
479                            self.node_mut(parent).left = Some(new_idx);
480                        },
481                        Ordering::Greater => { 
482                            //self.arena[parent].as_mut().unwrap().right = Some(new_idx);
483                            self.node_mut(parent).right = Some(new_idx);
484                        },
485                        Ordering::Equal => {}
486                    }
487                };
488
489                // Insert new node
490                self.arena.push(Some(AVLNode::new(new_idx, key, Some(parent), 1)));
491
492                // Walk up the tree to update heights and rebalance
493                let mut current = Some(parent);
494                while let Some(idx) = current {
495                    self.update_node_height(idx);
496                    self.restructure(idx);
497                    //current = self.arena[idx].as_mut().unwrap().parent;
498                    current = self.node_mut(idx).parent;
499                }
500            }
501            SearchResult::None => {
502                // Empty tree, insert root
503                let new_node = AVLNode::new(0, key, None, 1);
504                self.arena.push(Some(new_node));
505                self.root = Some(0);
506            }
507            SearchResult::Exists(_) => {}
508        }
509    }
510
511    /// Removes and returns an element from the AVL tree as an owned value.
512    //pub fn remove(&mut self, key: &T) -> Option<T> {
513    //    let target_index = match self.search(key) {
514    //pub fn remove(&mut self, key: &T) -> Option<T>
515    //where
516    //    //T: Keyed + Ord,
517    //    T: Ord,
518    //{
519    pub fn remove<Q>(&mut self, key: &Q) -> Option<T>
520    where
521        Q: Ord + ?Sized,
522        T: Borrow<Q>,
523    {
524        //let target_index = match self.search(key.key()) {
525        let target_index = match self.search(key) {
526            SearchResult::Exists(idx) => idx,
527            _ => return None,
528        };
529    
530        // Step 1: Find node to physically remove (node with ≤1 child)
531        let mut remove_index = target_index;
532        if self.node(remove_index).left.is_some() && self.node(remove_index).right.is_some() {
533            // Node has two children: find in-order successor
534            let mut succ_index = self.node(remove_index).right.unwrap();
535            while let Some(left) = self.node(succ_index).left {
536                succ_index = left;
537            }
538    
539            // Move successor's value into target node
540            //let succ_value = self.arena[succ_index].take().unwrap().value;
541            //self.node_mut(remove_index).value = succ_value;
542
543            // 1. Take the value out of the successor node.
544            let succ_value = self.node_mut(succ_index).value.take();
545            
546            // 2. Replace the target's value with the successor's, 
547            // getting the original target value back.
548            let original_value = self.node_mut(target_index).value.replace(succ_value.unwrap());
549            
550            // 3. Place the original target value into the successor node, 
551            // which we are about to remove.
552            self.node_mut(succ_index).value = original_value;
553            
554            // Now, the successor node can be safely removed, and it 
555            // contains the correct value to return.
556    
557            // Now remove the successor node (guaranteed ≤1 child)
558            remove_index = succ_index;
559        }
560    
561        // Step 2: Identify the child of the node to remove (if any)
562        let child_index = self.node(remove_index).left.or(self.node(remove_index).right);
563    
564        // Step 3: Update parent to point to the child
565        let parent_index = self.node(remove_index).parent;
566        if let Some(p_idx) = parent_index {
567            let parent = self.node_mut(p_idx);
568            if parent.left == Some(remove_index) {
569                parent.left = child_index;
570            } else {
571                parent.right = child_index;
572            }
573        } else {
574            // Removing root
575            self.root = child_index;
576        }
577    
578        // Step 4: Update child's parent
579        if let Some(c_idx) = child_index {
580            self.node_mut(c_idx).parent = parent_index;
581        }
582    
583        // Step 5: Take the node for return
584        let removed_value = self.arena[remove_index].take().map(|n| n.value);
585    
586        // Step 6: Walk up ancestors to update heights and rebalance
587        let mut current = parent_index;
588        while let Some(idx) = current {
589            self.update_node_height(idx);
590            self.restructure(idx);
591            current = self.node(idx).parent;
592        }
593    
594        removed_value?
595    }
596
597    // Utility functions
598    ////////////////////
599
600    /// Updates the height of an arbitrary node in an AVL tree
601    /// where leaf nodes are defined as having height 1
602    //fn update_node_height(&mut self, index: usize) {
603    //    let left = self.arena[index].as_mut().unwrap().left.map_or(0, |idx| self.arena[idx].as_mut().unwrap().height);
604    //    let right = self.arena[index].as_mut().unwrap().right.map_or(0, |idx| self.arena[idx].as_mut().unwrap().height);
605    //    // Works for internal and leaf nodes, because max(0, 0) + 1 = 1
606    //    self.arena[index].as_mut().unwrap().height = max(left, right) + 1
607    //}
608    fn update_node_height(&mut self, index: usize) {
609        let left = self.node_mut(index).left.map_or(0, |idx| self.node_mut(idx).height);
610        let right = self.node_mut(index).right.map_or(0, |idx| self.node_mut(idx).height);
611        // Works for internal and leaf nodes, because max(0, 0) + 1 = 1
612        self.node_mut(index).height = max(left, right) + 1
613    }
614
615    /// Rotate the subtree rooted at `root_idx` in the given direction.
616    /// `side` is the direction of the original heavy side (Side::Left or Side::Right).
617    fn rotate(&mut self, root_idx: usize, side: &Side) {
618        // Heavy child becomes the new root of the subtree
619        let child_idx = self.node_mut(root_idx)
620            .child(side)
621            .expect("Rotation requires heavy child");
622
623        // Move child's opposite subtree into root's heavy side
624        //let subtree = self.arena[child_idx].child(opposite(side));
625        let subtree = self.node_mut(child_idx).child(!side);
626        self.node_mut(root_idx).set_child(side, subtree);
627        if let Some(sub_idx) = subtree {
628            self.node_mut(sub_idx).parent = Some(root_idx);
629        }
630
631        // Update parent pointers
632        let parent_idx = self.node_mut(root_idx).parent;
633        self.node_mut(child_idx).parent = parent_idx;
634
635        if let Some(p_idx) = parent_idx {
636            if self.node_mut(p_idx).left == Some(root_idx) {
637                self.node_mut(p_idx).left = Some(child_idx);
638            } else {
639                self.node_mut(p_idx).right = Some(child_idx);
640            }
641        } else {
642            self.root = Some(child_idx);
643        }
644
645        // Make old root the child of new root
646        self.node_mut(child_idx).set_child(opposite(side), Some(root_idx));
647        self.node_mut(root_idx).parent = Some(child_idx);
648
649        // Update heights
650        self.update_node_height(root_idx);
651        self.update_node_height(child_idx);
652    }
653
654
655    /// Determines left-heavy (>0) or right-heavy (<0) balance factors for a given node index
656    /// The necessity for restructure operations can be determined agnostically by
657    /// `abs(balance_factor(index)) >= 2`
658    fn balance_factor(&self, index: usize) -> isize {
659        let node = &self.node(index);
660        let left = node.left.map_or(0, |l| self.node(l).height as isize);
661        let right = node.right.map_or(0, |r| self.node(r).height as isize);
662        left - right
663    }
664
665    /// Rebalances the subtree rooted at `index`.
666    /// Performs single or double rotations as necessary.
667    fn restructure(&mut self, index: usize) {
668
669        // Not all inserts require restructuring
670        let balance = self.balance_factor(index);
671        if balance.abs() < 2 {
672            return;
673        }
674
675        // Determine heavy side
676        let heavy_side = if balance > 1 { Side::Left } else { Side::Right };
677
678        // Determine the child index for the heavy side
679        let child_idx = match self.node(index).child(&heavy_side) {
680            Some(idx) => idx,
681            // SAFETY: A None value on the child violates the AVL invariant 
682            None => panic!("Error: Heavy child is None"),
683        };
684
685        // Double rotation check
686        //let child_balance = self.balance_factor(child_idx);
687        //if heavy_side == Side::Left && child_balance < 0 {
688        //    self.rotate(child_idx, &Side::Right);
689        //} else if heavy_side == Side::Right && child_balance > 0 {
690        //    self.rotate(child_idx, &Side::Left);
691        //}
692        match (&heavy_side, self.balance_factor(child_idx)) {
693            (Side::Left, b) if b < 0 => self.rotate(child_idx, &Side::Right), // LR
694            (Side::Right, b) if b > 0 => self.rotate(child_idx, &Side::Left), // RL
695            _ => {}
696        }
697
698        // Single rotation on parent
699        self.rotate(index, &heavy_side);
700    }
701
702    /// Produces a "snapshot" iterator over immutable references to the
703    /// tree in its current state.
704    pub fn iter(&self) -> InOrderIter<'_, T> {
705        InOrderIter::new(&self.arena, self.root)
706    }
707}
708
709pub struct InOrderIter<'a, T> {
710    arena: &'a [Option<AVLNode<T>>],
711    stack: Vec<usize>, // store indices, not references
712    current: Option<usize>,
713}
714impl<'a, T> InOrderIter<'a, T> {
715    fn new(arena: &'a [Option<AVLNode<T>>], root: Option<usize>) -> Self {
716        Self {
717            arena,
718            stack: Vec::new(),
719            current: root,
720        }
721    }
722}
723impl<'a, T> Iterator for InOrderIter<'a, T> {
724    type Item = &'a T;
725
726    fn next(&mut self) -> Option<Self::Item> {
727        while let Some(idx) = self.current {
728            if let Some(node) = self.arena[idx].as_ref() {
729                self.stack.push(idx);
730                self.current = node.left;
731                continue;
732            } else {
733                // Node was removed, skip
734                self.current = None;
735            }
736        }
737
738        if let Some(idx) = self.stack.pop() {
739            if let Some(node) = self.arena[idx].as_ref() {
740                self.current = node.right;
741                node.value.as_ref()
742            } else {
743                // Skip removed node
744                self.next()
745            }
746        } else {
747            None
748        }
749    }
750}
751
752#[test]
753fn avl_construction() {
754    let mut tree: AVLTree<u8> = AVLTree::new();
755
756    let v = [31, 13, 23, 39, 41, 43, 8, 17, 19];
757    // Produces the following AVL tree
758    // 
759    //           39      
760    //          /  \      
761    //        17    41      
762    //       /  \     \   
763    //     13   23     43
764    //     /   /  \           
765    //    8   19  31          
766    //
767    for e in v.iter() {
768        tree.insert(*e);
769    }
770
771    // Tests that the root is being updated properly
772    assert_eq!(tree.get_root().unwrap(), &39);
773    assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(39));
774    let root_node = &tree.node(tree.root.expect("nah, brah"));
775    assert_eq!(tree.node(root_node.left.unwrap()).value, Some(17));
776    assert_eq!(tree.node(root_node.right.unwrap()).value, Some(41));
777    assert_eq!(tree.node(0).left, None);
778    assert_eq!(tree.node(0).right, None);
779
780    assert_eq!(tree.node(tree.node(7).left.unwrap()).value, Some(13));
781    assert_eq!(tree.node(tree.node(7).right.unwrap()).value, Some(23));
782
783    let mut sorted = Vec::new();
784    for e in tree.iter() {
785        sorted.push(*e) 
786    }
787    assert_eq!(sorted, [8, 13, 17, 19, 23, 31, 39, 41, 43]);
788
789    let mut tree: AVLTree<u8> = AVLTree::new();
790    let v = [1, 2, 3, 4, 5, 6, 7];
791    // Produces the following AVL tree
792    // 
793    //          4
794    //        /   \
795    //      2       6
796    //     / \     / \
797    //    1   3   5   7
798    //       
799    for e in v.iter() {
800        tree.insert(*e);
801    }
802
803    assert_eq!(tree.get_root().unwrap(), &4);
804    assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(4));
805    let root_node = &tree.node(tree.root.expect("nah, brah"));
806    assert_eq!(tree.node(root_node.left.unwrap()).value, Some(2));
807    assert_eq!(tree.node(root_node.right.unwrap()).value, Some(6));
808    assert_eq!(tree.node(0).left, None);
809    assert_eq!(tree.node(0).right, None);
810
811    assert_eq!(tree.node(tree.node(5).left.unwrap()).value, Some(5));
812    assert_eq!(tree.node(tree.node(5).right.unwrap()).value, Some(7));
813
814    let mut sorted = Vec::new();
815    for e in tree.iter() {
816        sorted.push(*e) 
817    }
818    assert_eq!(sorted, [1, 2, 3, 4, 5, 6, 7]);
819
820    // Print visualization/debug
821    eprintln!("{tree:#?}");
822    //panic!();
823}
824
825#[test]
826fn avl_removals() {
827    let mut tree: AVLTree<u8> = AVLTree::new();
828
829    // Construct the following AVL tree
830    // 
831    //           39      
832    //          /  \      
833    //        17    41      
834    //       /  \     \   
835    //     13   23     43
836    //     /   /  \           
837    //    8   19  31          
838    //
839    let v = [31, 13, 23, 39, 41, 43, 8, 17, 19];
840    for e in v.iter() {
841        tree.insert(*e);
842    }
843
844    // Remove 31 which results in the following AVL tree
845    // 
846    //           39      
847    //          /  \      
848    //        17    41      
849    //       /  \     \   
850    //     13   23     43
851    //     /   /           
852    //    8   19            
853    //
854    assert_eq!(tree.get_root().unwrap(), &39);
855    assert!(tree.contains(&31));
856    let removed = tree.remove(&31).unwrap();
857    assert_eq!(removed, 31);
858    assert!(!tree.contains(&31));
859
860    assert_eq!(tree.node(tree.node(2).left.expect("")).value, Some(19));
861    assert_eq!(tree.node(2).right, None);
862
863    // Remove 41 which results in the following AVL tree
864    // 
865    //         17
866    //        /  \
867    //      13    39
868    //     /     /  \
869    //    8     23   43
870    //          /
871    //        19
872    //
873    assert!(tree.contains(&41));
874    let removed = tree.remove(&41).unwrap();
875    assert_eq!(removed, 41);
876    assert!(tree.remove(&41).is_none()); // Test that 41 was really removed
877    assert!(!tree.contains(&41));
878
879    // 39 now has L 23 and R 43
880    assert_eq!(tree.node(tree.node(3).left.expect("")).value, Some(23));
881    assert_eq!(tree.node(tree.node(3).right.expect("")).value, Some(43));
882
883    // 17 is now rooth with L 13 and R 39 
884    assert_eq!(tree.get_root().unwrap(), &17);
885    assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(17));
886    assert_eq!(tree.node(tree.node(7).left.expect("")).value, Some(13));
887    assert_eq!(tree.node(tree.node(7).right.expect("")).value, Some(39));
888    // The old root 39 now has L 23 and R 43
889    assert_eq!(tree.node(tree.node(3).left.expect("")).value, Some(23));
890    assert_eq!(tree.node(tree.node(3).right.expect("")).value, Some(43));
891
892    // Remove 8 which results in the following AVL tree
893    // 
894    //         23
895    //        /  \
896    //      17    39
897    //     /  \     \
898    //    13   19    43
899    //
900    assert!(tree.contains(&8));
901    let removed = tree.remove(&8).unwrap();
902    assert_eq!(removed, 8);
903    assert!(tree.remove(&8).is_none()); // Test that 8 was really removed
904    assert!(!tree.contains(&8));
905
906    // 23 is now rooth with L 17 and R 39
907    assert_eq!(tree.get_root().unwrap(), &23);
908    assert_eq!(tree.node(tree.root.expect("You fucked up")).value, Some(23));
909    assert_eq!(tree.node(tree.node(2).left.expect("")).value, Some(17));
910    assert_eq!(tree.node(tree.node(2).right.expect("")).value, Some(39));
911    // The old root 17 now has L 13 and R 19
912    assert_eq!(tree.node(tree.node(7).left.expect("")).value, Some(13));
913    assert_eq!(tree.node(tree.node(7).right.expect("")).value, Some(19));
914
915    // Print visualization/debug
916    eprintln!("{tree:#?}");
917    //panic!();
918}