binary_tree/bstree/
bstree.rs

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
/// ## Generic Search Binary Tree implementation
pub struct BinaryTree<T>
where
    T: Clone + Ord + Eq + std::fmt::Debug,
{
    /// Pointer holding the data can be None
    pub elem: Option<Box<T>>,
    /// Pointer to the right leaf
    pub right: Option<Box<BinaryTree<T>>>,
    /// Pointer to the left leaf
    pub left: Option<Box<BinaryTree<T>>>,
}

//pub type BinaryTreeNode<T> = BinaryTree<T>;

impl<T> BinaryTree<T>
where
    T: std::fmt::Debug + Clone + Ord,
{
    /// Creates a new `BinaryTree<T>`
    /// # Example
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// ```
    pub fn new(elem: T) -> Self {
        Self {
            elem: Some(Box::new(elem)),
            right: None,
            left: None,
        }
    }

    /// Deletes and returns the given element from the tree in O(log n)
    /// If the element is not in the tree returns None
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// let x = a.delete(1);
    /// assert_eq!(Some(x), a);
    /// ```
    pub fn delete(&mut self, del_elem: T) -> Option<T> {
        if let Some(ref mut elem) = self.elem {
            if del_elem < **elem {
                if let Some(left) = &mut self.left {
                    left.delete(del_elem)
                } else {
                    None
                }
            } else if del_elem > **elem {
                if let Some(right) = &mut self.right {
                    right.delete(del_elem)
                } else {
                    None
                }
            } else {
                // Element found, now delete it
                match (self.left.take(), self.right.take()) {
                    (None, right) => {
                        *self = BinaryTree {
                            elem: None,
                            left: None,
                            right,
                        };
                        Some(del_elem)
                    }
                    (left, None) => {
                        *self = BinaryTree {
                            elem: None,
                            left,
                            right: None,
                        };
                        Some(del_elem)
                    }
                    (Some(left), Some(right)) => {
                        let min_right = right.min().cloned();
                        *self = BinaryTree {
                            elem: min_right.map(Box::new),
                            left: Some(left),
                            right: Some(right),
                        };
                        Some(del_elem)
                    }
                }
            }
        } else {
            None
        }
    }

    /// Inserts the given element into the tree
    /// Time complexity -> O(log n)
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(1);
    /// ```
    pub fn insert(&mut self, new_elem: T) {
        match &mut self.elem {
            Some(ref mut elem) => {
                if new_elem < **elem {
                    if let Some(left) = &mut self.left {
                        left.insert(new_elem)
                    } else {
                        self.left = Some(Box::new(BinaryTree::new(new_elem)));
                    }
                } else if new_elem > **elem {
                    if let Some(right) = &mut self.right {
                        right.insert(new_elem)
                    } else {
                        self.right = Some(Box::new(BinaryTree::new(new_elem)));
                    }
                }
            }
            None => {
                self.elem = Some(Box::new(new_elem));
            }
        }
    }

    /// Returns true if the list is empty
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// let b = a.is_empty();
    /// assert_eq!(b, false);
    /// ```
    pub fn is_empty(&self) -> bool {
        self.elem.is_none() && self.right.is_none() && self.left.is_none()
    }

    /// Returns true if the elemen is in the tree with O(log n) complexity
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// let b = a.contains(1);
    /// assert_eq!(b, true);
    /// ```
    pub fn contains(&self, search_elem: T) -> bool {
        match &self.elem {
            Some(ref elem) => {
                if search_elem == **elem {
                    true
                } else if search_elem < **elem {
                    match &self.left {
                        Some(left) => left.contains(search_elem),
                        None => false,
                    }
                } else {
                    match &self.right {
                        Some(right) => right.contains(search_elem),
                        None => false,
                    }
                }
            }
            None => false,
        }
    }

    /// Clears/Deallocates the tree entirely
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// a.clear();
    /// assert_eq!(a.is_empty(), true);
    /// ```
    pub fn clear(&mut self) {
        self.elem = None;
        self.left = None;
        self.right = None;
    }

    /// Returns the maximum value of the tree in O(log n)
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// let x = a.max().unwrap();
    /// assert_eq!(x, 2);
    /// ```
    pub fn max(&self) -> Option<&T> {
        match &self.right {
            Some(right) => right.max(),
            None => self.elem.as_ref().map(|boxed_elem| &**boxed_elem),
        }
    }

    /// Returns the minimum value of the tree in O(log n)
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// let x = a.min().unwrap();
    /// assert_eq!(x, 1);
    /// ```
    pub fn min(&self) -> Option<&T> {
        match &self.left {
            Some(left) => left.min(),
            None => self.elem.as_ref().map(|boxed_elem| &**boxed_elem),
        }
    }

    /// Returns the height value of the tree in O(log n)
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// let x = a.height().unwrap();
    /// assert_eq!(x, 1);
    /// ```
    pub fn height(&self) -> usize {
        match (&self.left, &self.right) {
            (Some(left), Some(right)) => 1 + usize::max(left.height(), right.height()),
            (Some(left), None) => 1 + left.height(),
            (None, Some(right)) => 1 + right.height(),
            (None, None) => 1,
        }
    }

    /// Returns the total number of elements in the tree in O(n)
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// let x = a.count().unwrap();
    /// assert_eq!(x, 2);
    /// ```
    pub fn count(&self) -> usize {
        let left_count = self.left.as_ref().map_or(0, |left| left.count());
        let right_count = self.right.as_ref().map_or(0, |right| right.count());
        let current_count = if self.elem.is_some() { 1 } else { 0 };
        left_count + right_count + current_count
    }

    /// Prints to screen the elements in inorder
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// a.inorder();
    /// ```
    pub fn inorder(&self) {
        if let Some(left) = &self.left {
            left.inorder();
        }
        if let Some(elem) = &self.elem {
            println!("{:?}", elem);
        }
        if let Some(right) = &self.right {
            right.inorder();
        }
    }

    /// Prints to screen the elements in preorder
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// a.peorder();
    /// ```
    pub fn preorder(&self) {
        if let Some(elem) = &self.elem {
            println!("{:?}", elem);
        }
        if let Some(left) = &self.left {
            left.preorder();
        }
        if let Some(right) = &self.right {
            right.preorder();
        }
    }

    /// Prints to screen the elements in postorder
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.insert(2);
    /// a.postorder();
    /// ```
    pub fn postorder(&self) {
        if let Some(left) = &self.left {
            left.postorder();
        }
        if let Some(right) = &self.right {
            right.postorder();
        }
        if let Some(elem) = &self.elem {
            println!("{:?}", elem);
        }
    }

    /// Inserts all the elements in the vector in the tree
    /// Basic usage:
    /// ```
    /// let mut a = BinaryTree::new(1);
    /// a.vec_insert([1,2,3]);
    /// ```
    pub fn vec_insert(&mut self, elems: Vec<T>) {
        for i in elems {
            self.insert(i);
        }
    }
}