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
|
pub enum Ordering {
Less,
Equal,
Greater,
}
// TODO: la structure AVLNode est extrait comme un inductif à un cas
// au lieu d'être extrait comme une structure
struct AVLNode {
val: u32,
left: AVLTree,
right: AVLTree,
}
type AVLTree = Option<Box<AVLNode>>;
struct AVLTreeSet {
root: AVLTree,
}
impl AVLTreeSet {
pub fn new() -> Self {
Self { root: None }
}
pub fn find(&mut self, value: u32) -> bool {
let mut current_tree = &mut self.root;
while let Some(current_node) = current_tree {
match cmp(¤t_node.val, &value) {
Ordering::Less => current_tree = &mut current_node.right,
Ordering::Equal => return true,
Ordering::Greater => current_tree = &mut current_node.left,
}
}
false
}
pub fn insert(&mut self, value: u32) -> bool {
let mut current_tree = &mut self.root;
while let Some(current_node) = current_tree {
match cmp(¤t_node.val, &value) {
Ordering::Less => current_tree = &mut current_node.right,
Ordering::Equal => return false,
Ordering::Greater => current_tree = &mut current_node.left,
}
}
*current_tree = Some(Box::new(AVLNode {
val: value,
left: None,
right: None,
}));
true
}
}
fn cmp(a: &u32, other: &u32) -> Ordering {
if *a < *other {
Ordering::Less
} else if *a == *other {
Ordering::Equal
} else {
Ordering::Greater
}
}
|