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
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::cmp::max;
use std::fmt;

pub type Link<T> = Option<Box<Node<T>>>;

/// a Node struct to represent a bidirectional binary tree
/// holding pointers to the parent and two children, the left and right child
pub struct Node<T: Clone> {
    elem: T,
    parent: *mut Node<T>,
    left_child: Link<T>,
    right_child: Link<T>,
}

/// implement the node
impl<T: Clone> Node<T> {
    /// create a new node.
    pub fn new(elem: T) -> Box<Self> {
        Box::new(Node {
            elem,
            parent: ptr::null_mut(),
            left_child: None,
            right_child: None,
        })
    }

    pub fn get(&self) -> &T {
        &self.elem
    }

    pub fn get_mut(&mut self) -> &mut T {
        &mut self.elem
    }

    /// Check if node 'is' the same as this node.
    /// This just checks that the references are for the same 'Node<T>'
    pub fn is(&self, node: &Node<T>) -> bool {
        self as *const Node<T> == node as *const Node<T>
    }

    /// return true if this node is the left child, false if not
    pub fn check_left_child(&self, node: &Node<T>) -> bool {
        match self.left_child_opt() {
            Some(child) => child.is(node),
            None => false,
        }
    }

    /// return true if this node is the right child, false if not
    pub fn check_right_child(&self, node: &Node<T>) -> bool {
        match self.right_child_opt() {
            Some(child) => child.is(node),
            None => false,
        }
    }

    /// return true if this node is the left child of it's parent, false if not
    /// returns `None` if node doesn't have a parent.
    pub fn is_left_child(&self) -> Option<bool> {
        match self.parent_opt() {
            Some(parent) => Some(parent.check_left_child(self)),
            None => None,
        }
    }

    /// return true if this node is a leaf node, meaning it has no children.
    pub fn is_leaf(&self) -> bool {
        !self.has_left_child() && !self.has_right_child()
    }

    /// return true if this node has a valid left child and is not pointing to a null pointer
    pub fn has_left_child(&self) -> bool {
        self.left_child.is_some()
    }

    /// return true if this node has a valid right child and is not pointing to a null pointer 
    pub fn has_right_child(&self) -> bool {
        self.right_child.is_some()
    }

    /// return true if this node has a parent, false if not. 
    /// If it does not, then this node is the root of the tree.
    pub fn has_parent(&self) -> bool {
        !self.parent.is_null()
    }

    /// Safely set the left child node.
    /// Will drop any old left child node.
    pub fn set_left_child(&mut self, child: Link<T>) {
        self.take_left_child(); // Drops old left child
        if let Some(mut child) = child {
            child.set_parent(self);
            self.left_child = Some(child);
        }
    }

    /// Safely set the right child node.
    /// Will drop any old right child node.
    pub fn set_right_child(&mut self, child: Link<T>) {
        self.take_right_child(); // Drops old right child
        if let Some(mut child) = child {
            child.set_parent(self);
            self.right_child = Some(child);
        }
    }

    /// Safely set the node's parent.
    /// If the node already has a parent, this node will be removed from it.
    pub fn set_parent(&mut self, parent: *mut Node<T>) {
        self.remove_from_parent();
        self.parent = parent;
    }

    /// Returns a raw mutable reference to this node's left child.
    pub(crate) fn left_child_mut_ptr_opt(&mut self) -> Option<*mut Node<T>> {
        self.left_child.as_mut().map(|n| (&mut **n) as *mut Node<T>)
    }

    /// Returns a raw mutable reference to this node's right child.
    pub(crate) fn right_child_mut_ptr_opt(&mut self) -> Option<*mut Node<T>> {
        self.right_child.as_mut().map(|n| (&mut **n) as *mut Node<T>)
    }

    /// Safely returns a mutable reference to this node's left child.
    pub fn left_child_mut_opt(&mut self) -> Option<&mut Node<T>> {
        self.left_child.as_mut().map(|n| &mut **n)
    }

    /// Safely returns a mutable reference to this node's right child.
    pub fn right_child_mut_opt(&mut self) -> Option<&mut Node<T>> {
        self.right_child.as_mut().map(|n| &mut **n)
    }

    /// Safely returns a mutable reference to this node's parent.
    pub fn parent_mut_opt(&mut self) -> Option<&mut Node<T>> {
        if self.has_parent() {
            Some(unsafe { &mut *self.parent })
        } else {
            None
        }
    }

    /// Safely returns a reference to this node's left child.
    pub fn left_child_opt(&self) -> Option<&Node<T>> {
        self.left_child.as_ref().map(|n| &**n)
    }

    /// Safely returns a reference to this node's right child.
    pub fn right_child_opt(&self) -> Option<&Node<T>> {
        self.right_child.as_ref().map(|n| &**n)
    }

    /// Safely returns a reference to this node's parent.
    pub fn parent_opt(&self) -> Option<&Node<T>> {
        if self.has_parent() {
            Some(unsafe { &*self.parent })
        } else {
            None
        }
    }

    /// Remove and return the left child node.
    /// The returned node is owned by the caller
    pub fn take_left_child(&mut self) -> Link<T> {
        if let Some(mut child) = self.left_child.take() {
            child.parent = ptr::null_mut();
            Some(child)
        } else {
            None
        }
    }

    /// Remove and return the right child node.
    /// The returned node is owned by the caller
    pub fn take_right_child(&mut self) -> Link<T> {
        if let Some(mut child) = self.right_child.take() {
            child.parent = ptr::null_mut();
            Some(child)
        } else {
            None
        }
    }

    /// Safely remove a child node.
    fn remove_child(&mut self, child: &Node<T>) {
        let mut removed = false;
        if Some(child) == self.left_child_opt() {
            removed = true;
            self.left_child = None;
        }
        if Some(child) == self.right_child_opt() {
            assert!(!removed, "Node set as both left child and right child.");
            removed = true;
            self.right_child = None;
        }
        assert!(removed, "Node isn't a child of this node.");
    }

    /// Safely detach this node from it's parent.
    pub fn remove_from_parent(&mut self) {
        if self.has_parent() {
            let parent = unsafe { &mut *self.parent };
            self.parent = ptr::null_mut();
            parent.remove_child(self);
        }
    }

    /// return the height of this node recursivley
    #[inline]    
    pub fn height(&self) -> i32 {
        1 + max(
            self.left_child_opt().map_or(0, |node| node.height()),
            self.right_child_opt().map_or(0, |node| node.height())
        )
    }

    /// return the depth of this node, meaning the number of levels down it is 
    /// from the root of the tree, recrsive.
    #[inline]    
    pub fn depth(&self) -> i32 {
        match self.parent_opt() {
            Some(parent) => 1 + parent.depth(),
            None => 0
        }
    }

    /// return the size of the subtree recrusivley. 
    #[inline]    
    pub fn size(&self) -> i32 {
        let mut result = 1;
        if !self.is_leaf() {
            if let Some(left_child) = self.left_child_opt() {
                result += left_child.size();
            }
            if let Some(right_child) = self.right_child_opt() {
                result += right_child.size();
            }
        }
        result
    }

    /// Return a thin copy of this node, meaning keep all information besides the family pointers,
    /// these are nulled-out in order to avoid dangling or circular references.
    #[inline]
    pub fn copy(&self) -> Box<Node<T>> {
        Box::new(Node {
            elem: self.elem.clone(),
            parent: ptr::null_mut(),
            left_child: None,
            right_child: None,
        })
    }

    /// deep copy this node and it's subnodes. Recursivley traverse the tree in order and 
    /// thin copy the current node, then assign it's surroudning pointers recrusivley.
    #[inline]    
    pub fn deepcopy(&self) -> Box<Node<T>> {
        let mut temp_copy = self.copy();
        if let Some(child) = self.left_child_opt() {
            let child = child.deepcopy();
            temp_copy.set_left_child(Some(child));
        }
        if let Some(child) = self.right_child_opt() {
            let child = child.deepcopy();
            temp_copy.set_right_child(Some(child));
        }
        temp_copy
    }

    /// Randomly insert a node into the tree.
    pub fn insert_random(&mut self, node: Box<Node<T>>) {
        match rand::random() {
            true => {
                if let Some(child) = self.left_child_mut_opt() {
                    child.insert_random(node);
                } else {
                    self.set_left_child(Some(node));
                    return
                }
            },
            false => {
                if let Some(child) = self.right_child_mut_opt() {
                    child.insert_random(node);
                } else {
                    self.set_right_child(Some(node));
                    return
                }
            }
        }
    }

    /// Recrusively display the node and it's subnodes 
    /// Useful for visualizing the strucutre of the tree and debugging.
    /// Level is the depth of the tree, at the root it should be 0.
    pub fn display(&self, level: i32) {
        if let Some(child) = self.left_child_opt() {
            child.display(level + 1);
        }
        let tabs: String = (0..level)
            .map(|_| "\t")
            .collect::<Vec<_>>()
            .join("");
        println!("{}{:?}\n", tabs, self);
        if let Some(child) = self.right_child_opt() {
            child.display(level + 1);
        }
    }
}

impl<T: Clone> Deref for Node<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.elem
    }
}

impl<T: Clone> DerefMut for Node<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.elem
    }
}

impl<T: Clone> PartialEq for Node<T> {
    fn eq(&self, other: &Self) -> bool {
        self as *const Node<T> == other as *const Node<T>
    }
}

/// implement debut for the node to give a little more information for the node and 
/// make it easier to trace through a tree when a tree is displayed
impl<T: Clone> fmt::Debug for Node<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Node[{:p}]={{parent = {:?}, left = {:?}, right = {:?}}}",
          self, self.parent, self.left_child, self.right_child)
    }
}