avl_cont/
binary_search.rs

1use std::cmp;
2use std::cmp::Ordering;
3use std::collections::VecDeque;
4use std::mem;
5
6#[derive(Clone)]
7struct Node<T> {
8    value: T,
9    left: Option<usize>,
10    right: Option<usize>,
11    height: i8,
12}
13
14impl<T> Node<T> {
15    const fn new(value: T) -> Self {
16        Self {
17            value,
18            left: None,
19            right: None,
20            height: 0,
21        }
22    }
23}
24
25#[derive(Clone)]
26pub struct Tree<T> {
27    data: Vec<Option<Node<T>>>,
28    free: Vec<usize>,
29    root: usize,
30    size: usize,
31}
32
33impl<T> Default for Tree<T> {
34    fn default() -> Self {
35        Self {
36            data: Vec::new(),
37            free: Vec::new(),
38            root: 0,
39            size: 0,
40        }
41    }
42}
43
44impl<T> Tree<T> {
45    #[must_use]
46    pub const fn len(&self) -> usize {
47        self.size
48    }
49
50    #[must_use]
51    pub const fn is_empty(&self) -> bool {
52        self.size == 0
53    }
54
55    /// Returns a reference to the value at INDEX if it exists.
56    #[must_use]
57    pub fn get(&self, index: usize) -> Option<&T> {
58        self.data[index].as_ref().map(|n| &n.value)
59    }
60
61    // Tries to use a free'd index, otherwise pushes.
62    // Returns the index that was used.
63    fn insert_helper(&mut self, value: T) -> usize {
64        if let Some(n) = self.free.pop() {
65            self.data[n] = Some(Node::new(value));
66            n
67        } else {
68            self.data.push(Some(Node::new(value)));
69            self.len()
70        }
71    }
72
73    // Removes None values from the end of the data Vec.
74    // Removes corresponding indices from the free Vec.
75    fn clean_tail(&mut self) {
76        let mut popped = Vec::new();
77        while self.data.last().unwrap().is_none() {
78            self.data.pop();
79            popped.push(self.data.len());
80        }
81        self.free.retain(|i| {
82            popped.iter().position(|p| i == p).map_or(true, |n| {
83                popped.swap_remove(n);
84                false
85            })
86        });
87    }
88
89    fn update_and_balance(&mut self, mut visited_indices: Vec<usize>) {
90        // This is guarenteed to run at least once.
91        // The last run is always on the root index.
92        while let Some(index) = visited_indices.pop() {
93            let balance_factor = self.update_height(index);
94            let new_parent = self.balance_node(index, balance_factor);
95
96            // Set the grandfather to point to the subtree's new root.
97            match visited_indices.last() {
98                Some(n) => {
99                    let grandfather_data = self.data[*n].as_ref().unwrap();
100                    let child_is_left = grandfather_data.left.map_or(false, |left| index == left);
101
102                    if child_is_left {
103                        self.data[*n].as_mut().unwrap().left = Some(new_parent);
104                    } else {
105                        self.data[*n].as_mut().unwrap().right = Some(new_parent);
106                    }
107                }
108                None => self.root = new_parent,
109            }
110        }
111    }
112
113    // Update a node's height to be 1 + max_height between its children.
114    // If a node has no children, its height is calculated as 1 + -1 = 0.
115    // Returns the balance factor of the node. This is calcuated as the
116    // difference between its children's heights. If the right child has
117    // a height of 3 while the left has 1, the balance factor would be
118    // calculated as 2. This value or its inverse would require the tree
119    // to be rebalanced.
120    fn update_height(&mut self, index: usize) -> i8 {
121        let node_data = self.data[index].as_ref().unwrap();
122
123        let left_height: i8 = match node_data.left {
124            Some(n) => self.data[n].as_ref().unwrap().height,
125            None => -1,
126        };
127        let right_height: i8 = match node_data.right {
128            Some(n) => self.data[n].as_ref().unwrap().height,
129            None => -1,
130        };
131
132        let node_data = self.data[index].as_mut().unwrap();
133        node_data.height = 1 + cmp::max(left_height, right_height);
134
135        right_height - left_height
136    }
137
138    // Balance a node if one of its sides is two nodes taller than the other.
139    // In a sequence where the nodes connect A -> B -> C, a rotation is done
140    // such that node B points to its parent: A <- B -> C. If node B does not
141    // have a child in the same direction: A -> B and C <- B, node A is set
142    // to point to node C and C to B: A -> C -> B, then node C is set to
143    // point to node A: A <- C -> B. Returns the new parent's index.
144    fn balance_node(&mut self, index: usize, balance_factor: i8) -> usize {
145        let node_data = self.data[index].as_ref().unwrap();
146        match balance_factor {
147            -2 => {
148                let left_node = self.data[node_data.left.unwrap()].as_ref().unwrap();
149                match left_node.left {
150                    Some(_) => self.rotate_right(index),
151                    None => self.rotate_left_right(index),
152                }
153            }
154            2 => {
155                let right_node = self.data[node_data.right.unwrap()].as_ref().unwrap();
156                match right_node.right {
157                    Some(_) => self.rotate_left(index),
158                    None => self.rotate_right_left(index),
159                }
160            }
161            _ => index,
162        }
163    }
164
165    fn rotate_right(&mut self, index: usize) -> usize {
166        let left_index = self.data[index].as_ref().unwrap().left.unwrap();
167        let left_right_index = self.data[left_index].as_ref().unwrap().right;
168
169        let node_data = self.data[index].as_mut().unwrap();
170        node_data.left = left_right_index;
171
172        let left_data = self.data[left_index].as_mut().unwrap();
173        left_data.right = Some(index);
174
175        self.update_height(index);
176        self.update_height(left_index);
177
178        left_index
179    }
180
181    fn rotate_left(&mut self, index: usize) -> usize {
182        let right_index = self.data[index].as_ref().unwrap().right.unwrap();
183        let right_left_index = self.data[right_index].as_ref().unwrap().left;
184
185        let node_data = self.data[index].as_mut().unwrap();
186        node_data.right = right_left_index;
187
188        let right_data = self.data[right_index].as_mut().unwrap();
189        right_data.left = Some(index);
190
191        self.update_height(index);
192        self.update_height(right_index);
193
194        right_index
195    }
196
197    fn rotate_left_right(&mut self, index: usize) -> usize {
198        let left_index = self.data[index].as_ref().unwrap().left.unwrap();
199
200        self.data[index].as_mut().unwrap().left = Some(self.rotate_left(left_index));
201        self.rotate_right(index)
202    }
203
204    fn rotate_right_left(&mut self, index: usize) -> usize {
205        let right_index = self.data[index].as_ref().unwrap().right.unwrap();
206
207        self.data[index].as_mut().unwrap().right = Some(self.rotate_right(right_index));
208        self.rotate_left(index)
209    }
210}
211
212impl<T: Ord> Tree<T> {
213    /// Returns the index of VALUE if it is found.
214    pub fn contains(&self, value: T) -> Option<usize> {
215        if self.is_empty() {
216            return None;
217        }
218
219        let parent_index = match self.contains_helper(&value) {
220            (true, Some(n)) => *n.last().unwrap(),
221            (true, None) => return Some(self.root),
222            (false, _) => return None,
223        };
224        let parent_data = self.data[parent_index].as_ref().unwrap();
225
226        match value.cmp(&parent_data.value) {
227            Ordering::Less => parent_data.left,
228            Ordering::Greater => parent_data.right,
229            Ordering::Equal => unreachable!(),
230        }
231    }
232
233    // Returns a bool and all visited indices up to
234    // and including the (prospective) parent index.
235    fn contains_helper(&self, value: &T) -> (bool, Option<Vec<usize>>) {
236        let mut current_index = self.root;
237        let mut current_data = self.data[current_index].as_ref().unwrap();
238
239        if value == &current_data.value {
240            return (true, None);
241        }
242
243        let mut visited_indices = vec![current_index];
244
245        // Returns false if the value must be a child of a node
246        // that lacks a child on the correct side.
247        while current_data.left.is_some() || current_data.right.is_some() {
248            current_index = match value.cmp(&current_data.value) {
249                Ordering::Less => match current_data.left {
250                    Some(n) => n,
251                    None => return (false, Some(visited_indices)),
252                },
253                Ordering::Greater => match current_data.right {
254                    Some(n) => n,
255                    None => return (false, Some(visited_indices)),
256                },
257                Ordering::Equal => current_index,
258            };
259
260            current_data = self.data[current_index].as_ref().unwrap();
261            if value == &current_data.value {
262                return (true, Some(visited_indices));
263            }
264
265            visited_indices.push(current_index);
266        }
267
268        (false, Some(visited_indices))
269    }
270
271    /// Insert VALUE into the tree. Must be unique. Returns the index that was
272    /// used, or None if it wasn't inserted.
273    pub fn insert(&mut self, value: T) -> Option<usize> {
274        if self.is_empty() {
275            self.data.push(Some(Node::new(value)));
276            self.size = 1;
277            return Some(0);
278        }
279
280        let (false, Some(visited_indices)) = self.contains_helper(&value) else {
281            return None;
282        };
283        let parent_index = *visited_indices.last().unwrap();
284        let insert_index;
285
286        match &value.cmp(&self.data[parent_index].as_ref().unwrap().value) {
287            Ordering::Less => {
288                insert_index = self.insert_helper(value);
289                self.data[parent_index].as_mut().unwrap().left = Some(insert_index);
290            }
291            Ordering::Greater => {
292                insert_index = self.insert_helper(value);
293                self.data[parent_index].as_mut().unwrap().right = Some(insert_index);
294            }
295            Ordering::Equal => unreachable!(),
296        }
297
298        self.update_and_balance(visited_indices);
299        self.size += 1;
300        Some(insert_index)
301    }
302
303    /// Remove VALUE from the tree.
304    pub fn remove(&mut self, value: T) -> Option<T> {
305        if self.is_empty() {
306            return None;
307        }
308
309        let is_root = match self.remove_root_helper(&value) {
310            (b, None) => b,
311            (true, Some(return_val)) => return Some(return_val),
312            _ => unreachable!(),
313        };
314
315        let mut visited_indices = match self.contains_helper(&value) {
316            (true, None) => vec![self.root],
317            (true, Some(n)) => n,
318            (false, _) => return None,
319        };
320        let parent_index = *visited_indices.last().unwrap();
321        let parent_data = self.data[parent_index].as_ref().unwrap();
322        let child_is_left = value < parent_data.value;
323
324        let val_index = match (is_root, child_is_left) {
325            (true, _) => self.root,
326            (false, true) => parent_data.left.unwrap(),
327            (false, false) => parent_data.right.unwrap(),
328        };
329        let val_data = self.data[val_index].as_ref().unwrap();
330        let return_val;
331
332        if let (Some(val_left), Some(val_right)) = (val_data.left, val_data.right) {
333            let mut left_data = self.data[val_left].as_ref().unwrap();
334            let mut right_data = self.data[val_right].as_ref().unwrap();
335
336            let mut current_index;
337
338            // The node being removed will have its child tree modified.
339            // So it must be added to the visited indices to be updated
340            // and balanced. This is also done for every node visited
341            // up to the replacement. The root index was already added.
342            if !is_root {
343                visited_indices.push(val_index);
344            }
345
346            // Climbs to the replacement node on whichever side
347            // has the greater height. If it doesn't have a child,
348            // its parent's pointer is set to None.
349            let replace_index = if left_data.height > right_data.height {
350                current_index = val_left;
351                while let Some(n) = left_data.right {
352                    visited_indices.push(current_index);
353                    current_index = n;
354                    left_data = self.data[current_index].as_ref().unwrap();
355                }
356
357                if let Some(n) = left_data.left {
358                    self.data.swap(current_index, n);
359                    n
360                } else {
361                    self.data[*visited_indices.last().unwrap()]
362                        .as_mut()
363                        .unwrap()
364                        .right = None;
365                    current_index
366                }
367            } else {
368                current_index = val_right;
369                while let Some(n) = right_data.left {
370                    visited_indices.push(current_index);
371                    current_index = n;
372                    right_data = self.data[current_index].as_ref().unwrap();
373                }
374
375                if let Some(n) = right_data.right {
376                    self.data.swap(current_index, n);
377                    n
378                } else {
379                    self.data[*visited_indices.last().unwrap()]
380                        .as_mut()
381                        .unwrap()
382                        .left = None;
383                    current_index
384                }
385            };
386            self.free.push(replace_index);
387            let replace = Some(Node {
388                value: mem::replace(&mut self.data[replace_index], None)
389                    .unwrap()
390                    .value,
391                // If the value at the index is None, set pointer to None.
392                left: self.data[val_left].as_ref().map(|_| val_left),
393                right: self.data[val_right].as_ref().map(|_| val_right),
394                // The height of this new Node doesn't matter
395                // since it will be updated.
396                height: 0,
397            });
398
399            return_val = mem::replace(&mut self.data[val_index], replace)
400                .unwrap()
401                .value;
402        } else {
403            if let Some(child_index) = val_data.left.xor(val_data.right) {
404                if child_is_left {
405                    self.data[parent_index].as_mut().unwrap().left = Some(child_index);
406                } else {
407                    self.data[parent_index].as_mut().unwrap().right = Some(child_index);
408                }
409            } else if child_is_left {
410                self.data[parent_index].as_mut().unwrap().left = None;
411            } else {
412                self.data[parent_index].as_mut().unwrap().right = None;
413            }
414
415            self.free.push(val_index);
416            return_val = mem::replace(&mut self.data[val_index], None).unwrap().value;
417        }
418
419        self.update_and_balance(visited_indices);
420        self.clean_tail();
421        self.size -= 1;
422        Some(return_val)
423    }
424
425    // Handling trivial cases for removing a value at root.
426    fn remove_root_helper(&mut self, value: &T) -> (bool, Option<T>) {
427        let root_data = self.data[self.root].as_ref().unwrap();
428        if value == &root_data.value {
429            if self.size == 1 {
430                let return_val = self.data.pop().unwrap().unwrap().value;
431                self.free.clear();
432                self.data.clear();
433                self.root = 0;
434                self.size = 0;
435
436                return (true, Some(return_val));
437            }
438
439            if let Some(new_root) = root_data.left.xor(root_data.right) {
440                let return_val = mem::replace(&mut self.data[self.root], None).unwrap().value;
441                self.free.push(self.root);
442                self.root = new_root;
443                self.size -= 1;
444
445                self.clean_tail();
446                return (true, Some(return_val));
447            }
448
449            return (true, None);
450        }
451
452        (false, None)
453    }
454}
455
456pub struct Iter<T> {
457    data: Vec<Option<Node<T>>>,
458    queue: VecDeque<usize>,
459}
460
461impl<T> IntoIterator for Tree<T> {
462    type Item = T;
463    type IntoIter = Iter<T>;
464
465    fn into_iter(self) -> Self::IntoIter {
466        Iter {
467            data: self.data,
468            queue: VecDeque::from([self.root]),
469        }
470    }
471}
472
473impl<T> Iterator for Iter<T> {
474    type Item = T;
475
476    fn next(&mut self) -> Option<Self::Item> {
477        if let Some(current) = self.queue.pop_front() {
478            let current = mem::replace(&mut self.data[current], None).unwrap();
479
480            if let Some(n) = current.left {
481                self.queue.push_back(n);
482            }
483            if let Some(n) = current.right {
484                self.queue.push_back(n);
485            }
486
487            Some(current.value)
488        } else {
489            None
490        }
491    }
492}