-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search_tree.rs
85 lines (74 loc) · 2.1 KB
/
binary_search_tree.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
use crate::IoTDevice;
use std::mem;
type Tree = Option<Box<Node>>;
struct Node {
pub dev: IoTDevice,
left: Tree,
right: Tree,
}
impl Node {
pub fn new(dev: IoTDevice) -> Tree {
Some(Box::new(Node {
dev: dev,
left: None,
right: None,
}))
}
}
pub struct DeviceRegistry {
root: Tree,
pub length: u64,
}
impl DeviceRegistry {
pub fn new_empty() -> DeviceRegistry {
DeviceRegistry {
root: None,
length: 0,
}
}
pub fn add(&mut self, device: IoTDevice) {
self.length += 1;
let root = mem::replace(&mut self.root, None);
self.root = self.add_rec(root, device);
}
fn add_rec(&mut self, node: Tree, device: IoTDevice) -> Tree {
match node {
Some(mut n) => {
if n.dev.numerical_id <= device.numerical_id {
n.left = self.add_rec(n.left, device);
} else {
n.right = self.add_rec(n.right, device);
}
Some(n)
}
_ => Node::new(device),
}
}
pub fn find(&self, numerical_id: u64) -> Option<IoTDevice> {
self.find_r(&self.root, numerical_id)
}
fn find_r(&self, node: &Tree, numerical_id: u64) -> Option<IoTDevice> {
match node {
Some(n) => {
if n.dev.numerical_id == numerical_id {
Some(n.dev.clone())
} else if n.dev.numerical_id < numerical_id {
self.find_r(&n.left, numerical_id)
} else {
self.find_r(&n.right, numerical_id)
}
}
_ => None,
}
}
pub fn walk(&self, callback: impl Fn(&IoTDevice) -> ()) {
self.walk_in_order(&self.root, &callback);
}
fn walk_in_order(&self, node: &Tree, callback: &impl Fn(&IoTDevice) -> ()) {
if let Some(n) = node {
self.walk_in_order(&n.left, callback);
callback(&n.dev);
self.walk_in_order(&n.right, callback);
}
}
}