binary_tree/
binary_tree.rs

1extern crate lz_eytzinger_tree;
2
3use lz_eytzinger_tree::EytzingerTree;
4
5fn main() {
6    let mut binary_tree = BinaryTree::new();
7    binary_tree.insert(5);
8    binary_tree.insert(2);
9    binary_tree.insert(3);
10    binary_tree.insert(1);
11    binary_tree.insert(6);
12
13    println!("tree: {:?}", binary_tree);
14}
15
16#[derive(Debug)]
17pub struct BinaryTree<T> {
18    tree: EytzingerTree<T>,
19}
20
21impl<T> BinaryTree<T> {
22    fn new() -> Self {
23        Self {
24            tree: EytzingerTree::new(2),
25        }
26    }
27}
28
29const LEFT: usize = 0;
30const RIGHT: usize = 1;
31
32impl<T: Ord> BinaryTree<T> {
33    pub fn insert(&mut self, value: T) {
34        if let Some(root) = self.tree.root_mut() {
35            let mut current = root;
36            loop {
37                if &value == current.value() {
38                    return;
39                }
40
41                if &value < current.value() {
42                    match current.to_child(LEFT) {
43                        Ok(left) => {
44                            current = left;
45                            continue;
46                        }
47                        Err(mut current) => {
48                            current.set_child_value(LEFT, value);
49                            return;
50                        }
51                    }
52                }
53
54                match current.to_child(RIGHT) {
55                    Ok(right) => {
56                        current = right;
57                        continue;
58                    }
59                    Err(mut current) => {
60                        current.set_child_value(RIGHT, value);
61                        return;
62                    }
63                }
64            }
65        }
66        self.tree.set_root_value(value);
67    }
68}