1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use rand::seq::SliceRandom;
use rand::{thread_rng, Rng};

use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Debug, PartialEq)]
enum NodeColor {
    Red,
    Black,
}

#[derive(Debug)]
struct TreeNode<T> {
    pub color: NodeColor,
    pub key: T,
    pub parent: Option<Weak<RefCell<TreeNode<T>>>>,
    left: Option<Rc<RefCell<TreeNode<T>>>>,
    right: Option<Rc<RefCell<TreeNode<T>>>>,
}

impl<T> TreeNode<T> {
    fn new(val: T) -> Self {
        TreeNode {
            color: NodeColor::Red,
            key: val,
            parent: None,
            left: None,
            right: None,
        }
    }

    fn is_parent_red(&self) -> bool {
        match self.parent.as_ref() {
            None => false,
            Some(x) => x.upgrade().unwrap().borrow().color == NodeColor::Red,
        }
    }
}

#[derive(Debug)]
pub struct RBTree {
    root: Option<Rc<RefCell<TreeNode<u32>>>>,
}

impl RBTree {
    pub fn new() -> Self {
        RBTree { root: None }
    }

    fn rotate_left(&mut self, target: &Rc<RefCell<TreeNode<u32>>>) {
        {
            let o_p_option = &target.borrow().parent;

            let n_p_option = &target.borrow().right;

            if target.borrow().parent.is_none() {
                self.root = n_p_option.clone();
            }

            if let Some(o_p) = o_p_option {
                if RBTree::am_i_left_side(target) {
                    o_p.upgrade().unwrap().borrow_mut().left = n_p_option.clone();
                } else {
                    o_p.upgrade().unwrap().borrow_mut().right = n_p_option.clone();
                }
            }
            n_p_option.as_ref().unwrap().borrow_mut().parent = o_p_option.clone();
        }
        let n_p = target.borrow().right.as_ref().unwrap().clone();
        target.borrow_mut().parent = Some(Rc::downgrade(&n_p));

        // movedown
        if n_p.borrow().left.is_some() {
            target.borrow_mut().right = Some(n_p.borrow().left.as_ref().unwrap().clone());
            n_p.borrow_mut().left.as_ref().unwrap().borrow_mut().parent =
                Some(Rc::downgrade(target));
        } else {
            target.borrow_mut().right = None;
        }
        n_p.borrow_mut().left = Some(target.clone());
    }

    fn rotate_right(&mut self, target: &Rc<RefCell<TreeNode<u32>>>) {
        {
            let o_p_option = &target.borrow().parent;

            let n_p_option = &target.borrow().left;

            if target.borrow().parent.is_none() {
                self.root = n_p_option.clone();
            }

            if let Some(o_p) = o_p_option {
                if RBTree::am_i_left_side(target) {
                    o_p.upgrade().unwrap().borrow_mut().left = n_p_option.clone();
                } else {
                    o_p.upgrade().unwrap().borrow_mut().right = n_p_option.clone();
                }
            }
            n_p_option.as_ref().unwrap().borrow_mut().parent = o_p_option.clone();
        }
        let n_p = target.borrow().left.as_ref().unwrap().clone();
        target.borrow_mut().parent = Some(Rc::downgrade(&n_p));
        // movedown

        if n_p.borrow().right.is_some() {
            target.borrow_mut().left = Some(n_p.borrow().right.as_ref().unwrap().clone());
            n_p.borrow_mut().right.as_ref().unwrap().borrow_mut().parent =
                Some(Rc::downgrade(target));
        } else {
            target.borrow_mut().left = None;
        }
        n_p.borrow_mut().right = Some(target.clone());
    }
    fn find_successor(
        node: Option<Rc<RefCell<TreeNode<u32>>>>,
    ) -> Option<Rc<RefCell<TreeNode<u32>>>> {
        if node.as_ref().unwrap().borrow().right.is_some() {
            return Self::find_successor(node.as_ref().unwrap().borrow().right.clone());
        }
        return node;
    }

    fn find_replacement(node: &Rc<RefCell<TreeNode<u32>>>) -> Option<Rc<RefCell<TreeNode<u32>>>> {
        let node = node.borrow();
        if node.left.is_some() && node.right.is_some() {
            return Self::find_successor(node.left.clone());
        }

        if node.left.is_none() && node.right.is_none() {
            return None;
        }

        if node.left.is_some() {
            return node.left.clone();
        } else {
            return node.right.clone();
        }
    }

    pub fn delete(&mut self, val: u32) -> Result<(), String> {
        if self.root.is_none() {
            return Err(format!("Tree has no nodes").to_string());
        }
        let (found, option_to_delete) = self.binary_search(val);
        if !found {
            return Err(format!("Node not found").to_string());
        }
        let mut node_to_delete = option_to_delete.as_ref().unwrap();
        self.delete_node(&mut node_to_delete)
    }

    fn delete_node(
        &mut self,
        node_to_delete: &mut &Rc<RefCell<TreeNode<u32>>>,
    ) -> Result<(), String> {
        let u = Self::find_replacement(node_to_delete);

        let uv_black: bool = (u.is_none()
            || Self::get_color(u.as_ref().unwrap()) == NodeColor::Black)
            && Self::get_color(node_to_delete) == NodeColor::Black;
        let parent = if node_to_delete.borrow().parent.is_some() {
            node_to_delete.borrow().parent.as_ref().unwrap().upgrade()
        } else {
            None
        };

        if u.is_none() {
            // u is null so the node_to_delete is the leaf
            if node_to_delete.borrow().parent.is_none() {
                // Node is the root.
                self.root = None;
            } else {
                if uv_black {
                    // u & node_to_delete are black. node_to_delete is the leaf.
                    self.fix_double_black(node_to_delete);
                } else {
                    // u or node_to_delete is red
                    if Self::get_sibiling(node_to_delete).is_some() {
                        // Sibiling exists, so make it red.
                        Self::set_color_rc(node_to_delete, NodeColor::Red);
                    }
                }

                // Remove node_to_delete from tree
                if Self::am_i_left_side(node_to_delete) {
                    parent.as_ref().unwrap().borrow_mut().left = None;
                } else {
                    parent.as_ref().unwrap().borrow_mut().right = None;
                }
            }

            // Deleted node.
            return Ok(());
        }

        if node_to_delete.borrow().left.is_none() || node_to_delete.borrow().right.is_none() {
            // Node to delete has 1 child
            if node_to_delete.borrow().parent.is_none() {
                // Node to delete is the root. Assign the value of u to the node-to-delete.
                let u_key = Self::get_key(u.as_ref().unwrap());
                let mut root = self.root.as_ref().unwrap().borrow_mut();
                root.key = u_key;
                root.left = None;
                root.right = None;
            } else {
                // Detach node-to-delete from tree and move up.
                if Self::am_i_left_side(node_to_delete) {
                    parent.as_ref().unwrap().borrow_mut().left = u.clone();
                } else {
                    parent.as_ref().unwrap().borrow_mut().right = u.clone();
                }

                // Set u's parent to be a weak reference to "parent"
                u.as_ref().unwrap().borrow_mut().parent =
                    Some(Rc::downgrade(&parent.as_ref().unwrap().clone()));
                if uv_black {
                    self.fix_double_black(u.as_ref().unwrap());
                } else {
                    Self::set_color_rc(&mut u.as_ref().unwrap(), NodeColor::Black);
                }
            }
            return Ok(());
        }

        // node_to_delete has 2 children, swap values with successor and recurse.
        let u_key = Self::get_key(u.as_ref().unwrap());
        let node_to_delete_key = Self::get_key(node_to_delete);
        u.as_ref().unwrap().borrow_mut().key = node_to_delete_key;
        node_to_delete.borrow_mut().key = u_key;

        self.delete_node(&mut u.as_ref().unwrap())?;
        return Ok(());
    }

    fn fix_double_black(&mut self, node: &Rc<RefCell<TreeNode<u32>>>) {
        if node.borrow().parent.is_none() {
            // Node is root.
            return;
        }

        let sibiling = Self::get_sibiling(node);
        let parent = Self::get_parent(node);

        if sibiling.is_none() {
            // No sibiling, double black pushed up.
            self.fix_double_black(&parent.unwrap());
        } else {
            if Self::get_color(sibiling.as_ref().unwrap()) == NodeColor::Red {
                // Sibiling red
                Self::set_color_rc(&mut parent.as_ref().unwrap(), NodeColor::Red);
                Self::set_color_rc(&mut sibiling.as_ref().unwrap(), NodeColor::Black);

                if Self::am_i_left_side(sibiling.as_ref().unwrap()) {
                    // left case
                    self.rotate_right(parent.as_ref().unwrap());
                } else {
                    // right case
                    self.rotate_left(parent.as_ref().unwrap());
                }
                self.fix_double_black(node);
            } else {
                // Sibiling is black
                if Self::has_red_child(sibiling.as_ref().unwrap()) {
                    // at least 1 red child
                    if sibiling.as_ref().unwrap().borrow().left.is_some()
                        && Self::get_color(
                            sibiling.as_ref().unwrap().borrow().left.as_ref().unwrap(),
                        ) == NodeColor::Red
                    {
                        if Self::am_i_left_side(sibiling.as_ref().unwrap()) {
                            // left left
                            let sibiling_color = Self::get_color(sibiling.as_ref().unwrap());
                            let parent_color = Self::get_color(parent.as_ref().unwrap());
                            Self::set_color_rc(
                                &mut sibiling
                                    .as_ref()
                                    .unwrap()
                                    .borrow_mut()
                                    .left
                                    .as_ref()
                                    .unwrap(),
                                sibiling_color,
                            );
                            Self::set_color_rc(&mut sibiling.as_ref().unwrap(), parent_color);
                            self.rotate_right(parent.as_ref().unwrap());
                        } else {
                            // right right
                            let parent_color = Self::get_color(parent.as_ref().unwrap());
                            Self::set_color_rc(
                                &mut sibiling
                                    .as_ref()
                                    .unwrap()
                                    .borrow_mut()
                                    .left
                                    .as_ref()
                                    .unwrap(),
                                parent_color,
                            );
                            self.rotate_right(sibiling.as_ref().unwrap());
                            self.rotate_left(parent.as_ref().unwrap());
                        }
                    } else {
                        if Self::am_i_left_side(sibiling.as_ref().unwrap()) {
                            // left right
                            let parent_color = Self::get_color(parent.as_ref().unwrap());
                            Self::set_color_rc(
                                &mut sibiling
                                    .as_ref()
                                    .unwrap()
                                    .borrow_mut()
                                    .right
                                    .as_ref()
                                    .unwrap(),
                                parent_color,
                            );
                            self.rotate_left(sibiling.as_ref().unwrap());
                            self.rotate_right(parent.as_ref().unwrap());
                        } else {
                            // right right
                            let sibiling_color = Self::get_color(sibiling.as_ref().unwrap());
                            let parent_color = Self::get_color(parent.as_ref().unwrap());
                            Self::set_color_rc(
                                &mut sibiling
                                    .as_ref()
                                    .unwrap()
                                    .borrow_mut()
                                    .right
                                    .as_ref()
                                    .unwrap(),
                                sibiling_color,
                            );
                            Self::set_color_rc(&mut sibiling.as_ref().unwrap(), parent_color);
                            self.rotate_left(parent.as_ref().unwrap());
                        }
                    }
                    Self::set_color_rc(&mut parent.as_ref().unwrap(), NodeColor::Black);
                } else {
                    // 2 black children
                    Self::set_color_rc(&mut sibiling.as_ref().unwrap(), NodeColor::Red);

                    if Self::get_color(parent.as_ref().unwrap()) == NodeColor::Black {
                        self.fix_double_black(parent.as_ref().unwrap());
                    } else {
                        Self::set_color_rc(&mut parent.as_ref().unwrap(), NodeColor::Black);
                    }
                }
            }
        }
    }

    pub fn search(&mut self, val: u32) -> Result<(), String> {
        match self.binary_search(val) {
            (false, _) => Err(format!("Node not found").to_string()),
            (true, _) => Ok(()),
        }
    }

    fn binary_search(&mut self, val: u32) -> (bool, Option<Rc<RefCell<TreeNode<u32>>>>) {
        let mut parent_option = None;
        if self.root.is_none() {
            return (false, None);
        }
        let mut child_option = Some(self.root.as_ref().unwrap().clone());
        // THIS COPIES THE NODE, WHICH WE DONT WANT, COPY THE REF INSTEAD!!
        // let mut child_option = self.root.clone();

        // will be reset no matter what, setting it only so the compiler doesnt yell

        // While we have a child to navigate
        while child_option.is_some() {
            // we want to keep track of who the parent is, because child will be None when the loop ends
            parent_option = child_option;
            // a lot of stripping required to get to the actual node. as_ref borrows it so we can use it later
            // unwrap removes the option, and borrow borrows the value from the refcell
            let parent_node = parent_option.as_ref().unwrap();
            // Now that we own the actual node, we use it to get the key, and determine whether we go down left or right path
            if parent_node.borrow().key > val {
                child_option = match parent_node.borrow().left {
                    // if left exists, set the child to be equal to left
                    Some(ref y) => (Some(y.clone())),
                    // otherwise, remember which side to put it, and return
                    None => None,
                };
            } else if parent_node.borrow().key < val {
                child_option = match parent_node.borrow().right {
                    Some(ref y) => (Some(y.clone())),
                    None => None,
                };
            } else {
                // if the value is already in the tree, dont add it again
                return (true, parent_option);
            }
        }
        return (false, parent_option);
    }

    pub fn insert(&mut self, val: u32) -> Result<(), String> {
        if self.is_empty() {
            let mut new_node = TreeNode::new(val);
            new_node.color = NodeColor::Black;
            self.root = Some(Rc::new(RefCell::new(new_node)));
        } else {
            let (found, parent_option) = self.binary_search(val);
            if found {
                return Err(format!("Node already exists").to_string());
            }
            let child_belongs_on_left = val < parent_option.as_ref().unwrap().borrow().key;
            // Make a newchild with val
            let new_child_node = Rc::new(RefCell::new(TreeNode::new(val)));
            let new_child_ref_clone = new_child_node.clone();
            let new_child = Some(new_child_node);

            // Make a weak pointing to the parent
            let weak_parent_ref = Rc::downgrade(&parent_option.as_ref().unwrap().clone());
            // set it as the child's parent
            new_child.as_ref().unwrap().borrow_mut().parent = Some(weak_parent_ref);

            // put it on the side that it should be on (we found it earlier)
            if child_belongs_on_left {
                parent_option.as_ref().unwrap().borrow_mut().left = new_child;
            } else {
                parent_option.as_ref().unwrap().borrow_mut().right = new_child;
            }
            self.rebalance(new_child_ref_clone);
        }
        Ok(())
    }

    fn rebalance(&mut self, new_child: Rc<RefCell<TreeNode<u32>>>) {
        // let mut child_node = child.borrow();
        // using rebalancing cases from
        // https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion
        let mut child = new_child;
        loop {
            // child = new_child;
            if child.borrow().parent.is_none() {
                // Case 2
                Self::set_color_rc(&mut self.root.as_ref().unwrap(), NodeColor::Black);
                return;
            }
            if !child.borrow().is_parent_red() {
                // Case 3
                return;
            }
            // We know parent is red
            let mut parent = child.borrow().parent.as_ref().unwrap().upgrade().unwrap();
            // let parent_node = parent.borrow();
            if parent.borrow().parent.is_none() && parent.borrow().color == NodeColor::Red {
                // Case 6
                RBTree::set_color_rc(&mut &parent, NodeColor::Black);
                return;
            }
            // We know grandparent exists
            let grandparent = parent.borrow().parent.as_ref().unwrap().upgrade().unwrap();
            let uncle;

            // Check which side our parent is on to find our uncle (opposite side)
            let parent_left_side = RBTree::am_i_left_side(&parent);
            if parent_left_side {
                // if there is no (right side) uncle, or uncle is black:
                if grandparent.borrow().right.is_none()
                    || grandparent.borrow().right.as_ref().unwrap().borrow().color
                        == NodeColor::Black
                {
                    if !RBTree::am_i_left_side(&child) {
                        //Case 4

                        // &parent.borrow_mut().rotate_left();
                        self.rotate_left(&parent);
                        // child = parent;
                        parent = grandparent.borrow().left.as_ref().unwrap().clone();
                    }
                    // Case 5
                    self.rotate_right(&grandparent);
                    RBTree::set_color_rc(&mut &parent, NodeColor::Black);
                    RBTree::set_color_rc(&mut &grandparent, NodeColor::Red);

                    // grandparent.borrow_mut().rotate_right();
                    return;
                } else {
                    //Case 1
                    // if right side uncle exists
                    uncle = grandparent.borrow().right.as_ref().unwrap().clone();
                    RBTree::set_color_rc(&mut &parent, NodeColor::Black);
                    RBTree::set_color_rc(&mut &uncle, NodeColor::Black);
                    RBTree::set_color_rc(&mut &grandparent, NodeColor::Red);
                    // We've solved the problem at our node, but grandparent may have the same issue, so run it again.
                    child = grandparent;
                    continue;
                }
            } else {
                // if there is no (right side) uncle, or uncle is black:
                if grandparent.borrow().left.is_none()
                    || grandparent.borrow().left.as_ref().unwrap().borrow().color
                        == NodeColor::Black
                {
                    if RBTree::am_i_left_side(&child) {
                        //Case 4
                        self.rotate_right(&parent);

                        // parent.borrow_mut().rotate_right();

                        // child = parent;
                        parent = grandparent.borrow().right.as_ref().unwrap().clone();
                    }
                    // Case 5
                    self.rotate_left(&grandparent);
                    RBTree::set_color_rc(&mut &parent, NodeColor::Black);
                    RBTree::set_color_rc(&mut &grandparent, NodeColor::Red);

                    // grandparent.borrow_mut().rotate_left();
                    return;
                } else {
                    //Case 1
                    // if left side uncle exists
                    uncle = grandparent.borrow().left.as_ref().unwrap().clone();
                    RBTree::set_color_rc(&mut &parent, NodeColor::Black);
                    RBTree::set_color_rc(&mut &uncle, NodeColor::Black);
                    RBTree::set_color_rc(&mut &grandparent, NodeColor::Red);
                    // We've solved the problem at our node, but grandparent may have the same issue, so run it again.
                    child = grandparent;
                    continue;
                }
            }
        }
    }

    fn am_i_left_side(child: &Rc<RefCell<TreeNode<u32>>>) -> bool {
        let child_node = child.borrow();
        let parent = &child_node.parent.as_ref().unwrap().upgrade().unwrap();
        let parent_node = parent.borrow();
        // Check which side our parent is on
        match parent_node.left.as_ref() {
            Some(x) => x.borrow().key == child_node.key,
            None => false,
        }
    }

    fn get_sibiling(child: &Rc<RefCell<TreeNode<u32>>>) -> Option<Rc<RefCell<TreeNode<u32>>>> {
        let child_node = child.borrow();
        if child_node.parent.is_some() {
            let parent = &child_node.parent.as_ref().unwrap().upgrade().unwrap();
            let parent_node = parent.borrow();
            if Self::am_i_left_side(child) {
                return parent_node.right.clone();
            }
            return parent_node.left.clone();
        }
        return None
    }

    fn get_parent(child: &Rc<RefCell<TreeNode<u32>>>) -> Option<Rc<RefCell<TreeNode<u32>>>> {
        let child_node = child.borrow();
        if child_node.parent.is_some() {
            return child_node.parent.as_ref().unwrap().upgrade();
        }
        return None
    }

    fn has_red_child(child: &Rc<RefCell<TreeNode<u32>>>) -> bool {
        let child_node = child.borrow();

        if child_node.left.is_some()
            && Self::get_color(child_node.left.as_ref().unwrap()) == NodeColor::Red
        {
            return true;
        }
        if child_node.right.is_some()
            && Self::get_color(child_node.right.as_ref().unwrap()) == NodeColor::Red
        {
            return true;
        }
        return false;
    }

    fn get_color(node: &Rc<RefCell<TreeNode<u32>>>) -> NodeColor {
        let node = node.borrow();
        if node.color == NodeColor::Black {
            return NodeColor::Black;
        }
        return NodeColor::Red;
    }

    fn get_key(node: &Rc<RefCell<TreeNode<u32>>>) -> u32 {
        let node = node.borrow();
        return node.key;
    }

    fn set_color_rc(node: &mut &Rc<RefCell<TreeNode<u32>>>, color: NodeColor) {
        let mut node = node.borrow_mut();
        node.color = color;
    }

    pub fn get_num_leaves(&self) -> u32 {
        let mut count: u32 = 0;
        if self.is_empty() {
            return count;
        } else {
            count = private_get_num_leaves(&self.root, count);
        }

        fn private_get_num_leaves(
            node: &Option<Rc<RefCell<TreeNode<u32>>>>,
            mut current_count: u32,
        ) -> u32 {
            let node = node.as_ref().unwrap().borrow_mut();

            if !node.left.is_none() {
                current_count = private_get_num_leaves(&node.left, current_count);
            }
            if !node.right.is_none() {
                current_count = private_get_num_leaves(&node.right, current_count);
            }
            if node.left.is_none() && node.right.is_none() {
                current_count = current_count + 1;
            }

            current_count
        }

        count
    }

    pub fn height(&self) -> u32 {
        if self.is_empty() {
            return 0u32;
        }

        return recursive_get_depth(&self.root);

        fn recursive_get_depth(node: &Option<Rc<RefCell<TreeNode<u32>>>>) -> u32 {
            if node.is_none() {
                return 0u32;
            }

            let node = node.as_ref().unwrap().borrow_mut();

            let left_depth: u32 = recursive_get_depth(&node.left);
            let right_depth: u32 = recursive_get_depth(&node.right);

            if left_depth > right_depth {
                return left_depth + 1;
            }
            return right_depth + 1;
        }
    }

    pub fn is_empty(&self) -> bool {
        self.root.is_none()
    }

    fn get_nodes_in_order(&self) -> Vec<u32> {
        let mut vec = Vec::new();
        self.recursive_peek(&self.root, &mut vec);
        vec
    }

    fn recursive_peek(&self, node: &Option<Rc<RefCell<TreeNode<u32>>>>, vec: &mut Vec<u32>) {
        if node.is_none() {
            return;
        }

        let node = node.as_ref().unwrap().borrow_mut();

        self.recursive_peek(&node.left, vec);
        vec.push(node.key);
        self.recursive_peek(&node.right, vec);
    }

    pub fn print_nodes_in_order(&self) {
        if self.is_empty() {
            println!("Nothing in tree.");
        } else {
            let mut vec = Vec::new();
            self.recursive_peek(&self.root, &mut vec);
            println!("{:?}", vec);
        }
    }

    pub fn print_tree(&self) {
        println!("\nPrinting Tree in format <Left/Right Child> <Node Key> <Node Color>");
        recursive_print(&self.root, &"".to_string(), false, "Root".to_string());
        fn recursive_print(
            node: &Option<Rc<RefCell<TreeNode<u32>>>>,
            prefix_space: &String,
            is_right: bool,
            child_prefix: String,
        ) {
            if node.is_none() {
                let null_prefix = if is_right { "└ " } else { "├ " };
                println!("{}{}{} {}", prefix_space, null_prefix, child_prefix, "null");
                return;
            }

            let node = node.as_ref().unwrap().borrow();
            let color = if node.color == NodeColor::Black {
                "Black"
            } else {
                "Red"
            };
            let prefix_current = if is_right { "└ " } else { "├ " }; // Always prints L-node first then R-node

            // Print the current node
            println!(
                "{}{}{} {}:{}",
                prefix_space, prefix_current, child_prefix, node.key, color
            );

            // Increase the space
            let prefix_child = if is_right { "  " } else { "┤ " };
            let mut prefix_space = prefix_space.to_owned();
            prefix_space.push_str(&prefix_child);

            recursive_print(&node.left, &prefix_space, false, "🅻 ".to_string());
            recursive_print(&node.right, &prefix_space, true, "🆁 ".to_string());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nodes_sorted_rb() -> Result<(), String> {
        for _ in 0..100 {
            let mut my_tree = RBTree::new();
            let mut vec: Vec<u32> = (1..100).collect();
            vec.shuffle(&mut thread_rng());

            for i in 0..99 {
                my_tree.insert(vec[i])?;
            }
            let mut max = 0;

            for i in my_tree.get_nodes_in_order() {
                assert!(max < i);
                max = i;
            }
            assert!(my_tree.height() <= 9);
        }
        Ok(())
    }

    #[test]
    fn nodes_deleted_rb() -> Result<(), String> {
        let mut my_tree = RBTree::new();
        let iterations: usize = 100;
        let mut vec: Vec<u32> = (1..iterations as u32).collect();
        vec.shuffle(&mut thread_rng());

        for i in 0..(iterations - 1) {
            my_tree.insert(vec[i])?;
        }

        vec.shuffle(&mut thread_rng());

        let mut removed: Vec<u32> = Vec::new();

        for i in 0..(iterations - 1) {
            my_tree.delete(vec[i])?;
            removed.push(vec[i]);

            for j in 0..(iterations - 1) {
                if removed.contains(&vec[j]) {
                    assert!(my_tree.search(vec[j]).is_err());
                } else {
                    assert!(my_tree.search(vec[j]).is_ok());
                }
            }
        }

        assert!(my_tree.height() <= 9);
        Ok(())
    }
}