binary_tree/bstree/
bstree.rs

1/// ## Generic Search Binary Tree implementation
2pub struct BinaryTree<T>
3where
4    T: Clone + Ord + Eq + std::fmt::Debug,
5{
6    /// Pointer holding the data can be None
7    pub elem: Option<Box<T>>,
8    /// Pointer to the right leaf
9    pub right: Option<Box<BinaryTree<T>>>,
10    /// Pointer to the left leaf
11    pub left: Option<Box<BinaryTree<T>>>,
12}
13
14//pub type BinaryTreeNode<T> = BinaryTree<T>;
15
16impl<T> BinaryTree<T>
17where
18    T: std::fmt::Debug + Clone + Ord,
19{
20    /// Creates a new `BinaryTree<T>`
21    /// # Example
22    /// Basic usage:
23    /// ```
24    /// let mut a = BinaryTree::new(1);
25    /// ```
26    pub fn new(elem: T) -> Self {
27        Self {
28            elem: Some(Box::new(elem)),
29            right: None,
30            left: None,
31        }
32    }
33
34    /// Deletes and returns the given element from the tree in O(log n)
35    /// If the element is not in the tree returns None
36    /// Basic usage:
37    /// ```
38    /// let mut a = BinaryTree::new(1);
39    /// let x = a.delete(1);
40    /// assert_eq!(Some(x), a);
41    /// ```
42    pub fn delete(&mut self, del_elem: T) -> Option<T> {
43        if let Some(ref mut elem) = self.elem {
44            if del_elem < **elem {
45                if let Some(left) = &mut self.left {
46                    left.delete(del_elem)
47                } else {
48                    None
49                }
50            } else if del_elem > **elem {
51                if let Some(right) = &mut self.right {
52                    right.delete(del_elem)
53                } else {
54                    None
55                }
56            } else {
57                // Element found, now delete it
58                match (self.left.take(), self.right.take()) {
59                    (None, right) => {
60                        *self = BinaryTree {
61                            elem: None,
62                            left: None,
63                            right,
64                        };
65                        Some(del_elem)
66                    }
67                    (left, None) => {
68                        *self = BinaryTree {
69                            elem: None,
70                            left,
71                            right: None,
72                        };
73                        Some(del_elem)
74                    }
75                    (Some(left), Some(right)) => {
76                        let min_right = right.min().cloned();
77                        *self = BinaryTree {
78                            elem: min_right.map(Box::new),
79                            left: Some(left),
80                            right: Some(right),
81                        };
82                        Some(del_elem)
83                    }
84                }
85            }
86        } else {
87            None
88        }
89    }
90
91    /// Inserts the given element into the tree
92    /// Time complexity -> O(log n)
93    /// Basic usage:
94    /// ```
95    /// let mut a = BinaryTree::new(1);
96    /// a.insert(1);
97    /// ```
98    pub fn insert(&mut self, new_elem: T) {
99        match &mut self.elem {
100            Some(ref mut elem) => {
101                if new_elem < **elem {
102                    if let Some(left) = &mut self.left {
103                        left.insert(new_elem)
104                    } else {
105                        self.left = Some(Box::new(BinaryTree::new(new_elem)));
106                    }
107                } else if new_elem > **elem {
108                    if let Some(right) = &mut self.right {
109                        right.insert(new_elem)
110                    } else {
111                        self.right = Some(Box::new(BinaryTree::new(new_elem)));
112                    }
113                }
114            }
115            None => {
116                self.elem = Some(Box::new(new_elem));
117            }
118        }
119    }
120
121    /// Returns true if the list is empty
122    /// Basic usage:
123    /// ```
124    /// let mut a = BinaryTree::new(1);
125    /// let b = a.is_empty();
126    /// assert_eq!(b, false);
127    /// ```
128    pub fn is_empty(&self) -> bool {
129        self.elem.is_none() && self.right.is_none() && self.left.is_none()
130    }
131
132    /// Returns true if the elemen is in the tree with O(log n) complexity
133    /// Basic usage:
134    /// ```
135    /// let mut a = BinaryTree::new(1);
136    /// let b = a.contains(1);
137    /// assert_eq!(b, true);
138    /// ```
139    pub fn contains(&self, search_elem: T) -> bool {
140        match &self.elem {
141            Some(ref elem) => {
142                if search_elem == **elem {
143                    true
144                } else if search_elem < **elem {
145                    match &self.left {
146                        Some(left) => left.contains(search_elem),
147                        None => false,
148                    }
149                } else {
150                    match &self.right {
151                        Some(right) => right.contains(search_elem),
152                        None => false,
153                    }
154                }
155            }
156            None => false,
157        }
158    }
159
160    /// Clears/Deallocates the tree entirely
161    /// Basic usage:
162    /// ```
163    /// let mut a = BinaryTree::new(1);
164    /// a.insert(2);
165    /// a.clear();
166    /// assert_eq!(a.is_empty(), true);
167    /// ```
168    pub fn clear(&mut self) {
169        self.elem = None;
170        self.left = None;
171        self.right = None;
172    }
173
174    /// Returns the maximum value of the tree in O(log n)
175    /// Basic usage:
176    /// ```
177    /// let mut a = BinaryTree::new(1);
178    /// a.insert(2);
179    /// let x = a.max().unwrap();
180    /// assert_eq!(x, 2);
181    /// ```
182    pub fn max(&self) -> Option<&T> {
183        match &self.right {
184            Some(right) => right.max(),
185            None => self.elem.as_ref().map(|boxed_elem| &**boxed_elem),
186        }
187    }
188
189    /// Returns the minimum value of the tree in O(log n)
190    /// Basic usage:
191    /// ```
192    /// let mut a = BinaryTree::new(1);
193    /// a.insert(2);
194    /// let x = a.min().unwrap();
195    /// assert_eq!(x, 1);
196    /// ```
197    pub fn min(&self) -> Option<&T> {
198        match &self.left {
199            Some(left) => left.min(),
200            None => self.elem.as_ref().map(|boxed_elem| &**boxed_elem),
201        }
202    }
203
204    /// Returns the height value of the tree in O(log n)
205    /// Basic usage:
206    /// ```
207    /// let mut a = BinaryTree::new(1);
208    /// a.insert(2);
209    /// let x = a.height().unwrap();
210    /// assert_eq!(x, 1);
211    /// ```
212    pub fn height(&self) -> usize {
213        match (&self.left, &self.right) {
214            (Some(left), Some(right)) => 1 + usize::max(left.height(), right.height()),
215            (Some(left), None) => 1 + left.height(),
216            (None, Some(right)) => 1 + right.height(),
217            (None, None) => 1,
218        }
219    }
220
221    /// Returns the total number of elements in the tree in O(n)
222    /// Basic usage:
223    /// ```
224    /// let mut a = BinaryTree::new(1);
225    /// a.insert(2);
226    /// let x = a.count().unwrap();
227    /// assert_eq!(x, 2);
228    /// ```
229    pub fn count(&self) -> usize {
230        let left_count = self.left.as_ref().map_or(0, |left| left.count());
231        let right_count = self.right.as_ref().map_or(0, |right| right.count());
232        let current_count = if self.elem.is_some() { 1 } else { 0 };
233        left_count + right_count + current_count
234    }
235
236    /// Prints to screen the elements in inorder
237    /// Basic usage:
238    /// ```
239    /// let mut a = BinaryTree::new(1);
240    /// a.insert(2);
241    /// a.inorder();
242    /// ```
243    pub fn inorder(&self) {
244        if let Some(left) = &self.left {
245            left.inorder();
246        }
247        if let Some(elem) = &self.elem {
248            println!("{:?}", elem);
249        }
250        if let Some(right) = &self.right {
251            right.inorder();
252        }
253    }
254
255    /// Prints to screen the elements in preorder
256    /// Basic usage:
257    /// ```
258    /// let mut a = BinaryTree::new(1);
259    /// a.insert(2);
260    /// a.peorder();
261    /// ```
262    pub fn preorder(&self) {
263        if let Some(elem) = &self.elem {
264            println!("{:?}", elem);
265        }
266        if let Some(left) = &self.left {
267            left.preorder();
268        }
269        if let Some(right) = &self.right {
270            right.preorder();
271        }
272    }
273
274    /// Prints to screen the elements in postorder
275    /// Basic usage:
276    /// ```
277    /// let mut a = BinaryTree::new(1);
278    /// a.insert(2);
279    /// a.postorder();
280    /// ```
281    pub fn postorder(&self) {
282        if let Some(left) = &self.left {
283            left.postorder();
284        }
285        if let Some(right) = &self.right {
286            right.postorder();
287        }
288        if let Some(elem) = &self.elem {
289            println!("{:?}", elem);
290        }
291    }
292
293    /// Inserts all the elements in the vector in the tree
294    /// Basic usage:
295    /// ```
296    /// let mut a = BinaryTree::new(1);
297    /// a.vec_insert([1,2,3]);
298    /// ```
299    pub fn vec_insert(&mut self, elems: Vec<T>) {
300        for i in elems {
301            self.insert(i);
302        }
303    }
304}