~nerosnm/advela

ref: 34c6397938bf13319ad5e711b9a107fd4006c2de advela/src/node.rs -rw-r--r-- 4.1 KiB
34c63979Søren Mortensen Initial commit 11 months ago
                                                                                
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
//! A node in an [AvlTree][crate::tree::AvlTree].

use std::cmp::Ordering;

pub struct AvlNode<T>
where
    T: Ord,
{
    val: T,
    left: Option<Box<AvlNode<T>>>,
    right: Option<Box<AvlNode<T>>>,
}

impl<T> AvlNode<T>
where
    T: Ord,
{
    /// Create a new node containing the given value, with no children.
    pub fn new(val: T) -> Self {
        Self {
            val,
            left: None,
            right: None,
        }
    }

    /// Set the left child of this node to the given node.
    pub fn set_left<V>(&mut self, val: V)
    where
        V: Into<AvlNode<T>>,
    {
        self.left = Some(val.into().into());
    }

    /// Set the right child of this node to the given node.
    pub fn set_right<V>(&mut self, val: V)
    where
        V: Into<AvlNode<T>>,
    {
        self.right = Some(val.into().into());
    }

    /// Insert a value into the subtree that has this node as its root.
    ///
    /// If the value already exists in the subtree, nothing will be changed.
    pub fn insert<V>(&mut self, val: V)
    where
        V: Into<T>,
    {
        let val = val.into();

        match val.cmp(&self.val) {
            Ordering::Equal => {
                // We can't insert duplicate values, so don't do anything.
            }
            Ordering::Less => {
                if let Some(ref mut left) = self.left {
                    left.insert(val);
                } else {
                    self.set_left(val);
                }
            }
            Ordering::Greater => {
                if let Some(ref mut right) = self.right {
                    right.insert(val);
                } else {
                    self.set_right(val);
                }
            }
        }
    }

    /// Return whether the given value is present anywhere in the subtree with
    /// this node as its root.
    pub fn contains(&self, val: &T) -> bool {
        match val.cmp(&self.val) {
            Ordering::Equal => true,
            Ordering::Less => self
                .left
                .as_ref()
                .map(|left| left.contains(val))
                .unwrap_or(false),
            Ordering::Greater => self
                .right
                .as_ref()
                .map(|right| right.contains(val))
                .unwrap_or(false),
        }
    }
}

#[cfg(feature = "print")]
impl<T> AvlNode<T>
where
    T: Ord,
    T: std::fmt::Display,
{
    /// Print the subtree that has this node as its root node.
    pub fn print(&self) -> String {
        self.print_at_level(0)
    }

    /// Print the subtree that has this node as its root node, adding `2 *
    /// level` spaces to the beginning of each line, to represent depth in a
    /// containing tree.
    fn print_at_level(&self, level: usize) -> String {
        let mut buf = String::new();

        (0..level).for_each(|_| buf.push_str("  "));
        buf.push_str(&format!("{}", self.val));
        buf.push('\n');

        if let Some(ref left) = self.left {
            buf.push_str(&left.print_at_level(level + 1));
        }

        if let Some(ref right) = self.right {
            buf.push_str(&right.print_at_level(level + 1));
        }

        buf
    }
}

impl<T> From<T> for AvlNode<T>
where
    T: Ord,
{
    fn from(val: T) -> Self {
        Self::new(val)
    }
}

impl<T> From<T> for Box<AvlNode<T>>
where
    T: Ord,
{
    fn from(val: T) -> Self {
        Box::new(val.into())
    }
}

#[cfg(test)]
pub struct AvlNodeBuilder<T>
where
    T: Ord,
{
    val: T,
    left: Option<T>,
    right: Option<T>,
}

#[cfg(test)]
impl<T> AvlNodeBuilder<T>
where
    T: Ord,
{
    pub fn new(val: T) -> Self {
        Self {
            val,
            left: None,
            right: None,
        }
    }

    pub fn left(mut self, val: T) -> Self {
        self.left = Some(val);
        self
    }

    pub fn right(mut self, val: T) -> Self {
        self.right = Some(val);
        self
    }

    pub fn build(self) -> AvlNode<T> {
        let mut node = AvlNode::<T>::new(self.val);

        if let Some(left) = self.left {
            node.set_left(left);
        }

        if let Some(right) = self.right {
            node.set_right(right);
        }

        node
    }
}