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
//! Data structures and algorithms for testing purposes.

use std::mem;
use std::cmp;

use Node;
use NodeMut;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Level {
    Balanced(u32),
    Imbalanced(u32),
}

impl Level {
    pub fn is_balanced(self) -> bool {
        if let Level::Balanced(_) = self {
            true
        } else {
            false
        }
    }

    pub fn as_u32(self) -> u32 {
        match self {
            Level::Balanced(e) |
            Level::Imbalanced(e) => e,
        }
    }
}

/// Recursively calculate the level of this node and check whether it is
/// balanced.
///
/// `level = height + 1`. Recursive, hence risk of stack blow up depending on
/// the height of the tree! The node is considered balanced if, at every node,
/// the difference in levels of the child nodes is not greater than `tolerance`.
pub fn compute_level<N: Node>(node: &N, tolerance: u32) -> Level {
    use test::Level::*;

    let llevel = node.left().map_or(Balanced(0), |n| compute_level(n, tolerance));
    let rlevel = node.right().map_or(Balanced(0), |n| compute_level(n, tolerance));

    if llevel.is_balanced() && rlevel.is_balanced() {
        let max = cmp::max(llevel.as_u32(), rlevel.as_u32());
        let min = cmp::min(llevel.as_u32(), rlevel.as_u32());
        if max - min > tolerance {
            Imbalanced(max + 1)
        } else {
            Balanced(max + 1)
        }
    } else {
        Imbalanced(cmp::max(llevel.as_u32(), rlevel.as_u32()) + 1)
    }
}

#[derive(Debug)]
/// A minimal `Node` implementation.
///
/// ## When should you use `TestNode`?
///
/// You should not use `TestNode` for anything, except may be to get to know what
/// a binary tree is!
pub struct TestNode<T> {
    pub val: T,
    pub left: Option<Box<TestNode<T>>>,
    pub right: Option<Box<TestNode<T>>>,
}

impl<T> TestNode<T> {
    pub fn new(val: T) -> TestNode<T> {
        TestNode {
            val: val,
            left: None,
            right: None,
        }
    }
}

impl<T> Node for TestNode<T> {
    type Value = T;

    fn left(&self) -> Option<&Self> {
        self.left.as_ref().map(|st| &**st)
    }

    fn right(&self) -> Option<&Self> {
        self.right.as_ref().map(|st| &**st)
    }

    fn value(&self) -> &T {
        &self.val
    }
}

impl<T> NodeMut for TestNode<T> {
    type NodePtr = Box<TestNode<T>>;

    fn detach_left(&mut self) -> Option<Self::NodePtr> {
        self.left.take()
    }

    fn detach_right(&mut self) -> Option<Self::NodePtr> {
        self.right.take()
    }

    fn insert_left(&mut self, mut st: Option<Self::NodePtr>) -> Option<Self::NodePtr> {
        mem::swap(&mut self.left, &mut st);
        st
    }

    fn insert_right(&mut self, mut st: Option<Self::NodePtr>) -> Option<Self::NodePtr> {
        mem::swap(&mut self.right, &mut st);
        st
    }

    fn value_mut(&mut self) -> &mut T {
        &mut self.val
    }

    fn into_parts(self) -> (T, Option<Self::NodePtr>, Option<Self::NodePtr>) {
        (self.val, self.left, self.right)
    }

    fn left_mut(&mut self) -> Option<&mut Self> {
        self.left.as_mut().map(|l| &mut **l)
    }

    fn right_mut(&mut self) -> Option<&mut Self> {
        self.right.as_mut().map(|r| &mut **r)
    }
}

#[cfg(test)]
mod tests {
    use super::TestNode;
    use Node;
    use NodeMut;

    fn new_node<T>(val: T) -> Box<TestNode<T>> {
        Box::new(TestNode::new(val))
    }

    fn test_tree() -> TestNode<u32> {
        TestNode {
            val: 20,
            left: Some(new_node(10)),
            right: Some(Box::new(TestNode {
                val: 30,
                left: Some(new_node(25)),
                right: None,
            })),
        }
    }

    #[test]
    fn rotate() {
        let mut tt = test_tree();

        tt.rotate_left().unwrap();
        assert_eq!(*tt.value(),                    30);
        assert_eq!(tt.left.as_ref().unwrap().val,  20);
        assert_eq!(tt.left.as_ref().unwrap()
                     .left.as_ref().unwrap().val,  10);
        assert_eq!(tt.left.as_ref().unwrap()
                     .right.as_ref().unwrap().val, 25);

        tt.rotate_right().unwrap();
        assert_eq!(*tt.value(),                    20);
        assert_eq!(tt.left.as_ref().unwrap().val,  10);
        assert_eq!(tt.right.as_ref().unwrap().val, 30);
        assert_eq!(tt.right.as_ref().unwrap()
                     .left.as_ref().unwrap().val,  25);
    }

    #[test]
    fn walk() {
        use WalkAction::*;

        let mut tt = test_tree();
        let mut steps = vec![Right, Left, Stop];
        {
            let mut step_iter = steps.drain(..);
            tt.walk_reshape(|_| step_iter.next().unwrap(),
                            |st| assert_eq!(st.val, 25),
                            |st, action| {
                                match action {
                                    Right => assert_eq!(st.val, 20),
                                    Left => assert_eq!(st.val, 30),
                                    Stop => unreachable!(),
                                }
                            });
        }
        assert_eq!(steps.len(), 0);
    }

    #[test]
    fn remove() {
        let mut tt = test_tree();
        let tn = tt.right.as_mut().unwrap().try_remove(|_, _| ());
        assert_eq!(tn.unwrap().value(), &30);
        assert_eq!(tt.right.as_ref().unwrap().value(), &25);
        let mut tt2 = test_tree();
        {
            let right = tt2.right.as_mut().unwrap();
            right.right = Some(new_node(40));
        }
        let tn = tt2.right.as_mut().unwrap().try_remove(|_, _| ());
        assert_eq!(tn.unwrap().value(), &30);
        assert_eq!(tt.right.as_ref().unwrap().value(), &25);
    }

    #[test]
    fn stack_blow() {
        use iter::IntoIter;
        let mut pt = new_node(20);
        for _ in 0..200000 {
            let mut pt2 = new_node(20);
            pt2.insert_left(Some(pt));
            pt = pt2;
        }
        // comment out the line below to observe a stack overflow
        let _: IntoIter<TestNode<_>> = IntoIter::new(Some(pt));
    }
}