1use std::collections::{BTreeSet};
2
3
4#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
8pub struct NodeID {
9 index: usize,
10 version: usize,
11}
12
13#[derive(Clone, PartialEq, Eq)]
15pub struct Tree<T: Clone> {
16 roots: Vec<NodeID>,
17 parents: Vec<Option<NodeID>>,
18 children: Vec<Vec<NodeID>>,
19 data: Vec<Option<T>>,
20 versions: Vec<usize>,
21 empty: BTreeSet<usize>,
22}
23
24struct IterStack<'a> {
26 group: &'a Vec<NodeID>,
27 next_index: usize,
28}
29
30pub struct DepthIter<'a, T: Clone> {
32 tree: &'a Tree<T>,
33 stacks: Vec<IterStack<'a>>,
34}
35
36
37pub struct BreadthIter<'a, T: Clone> {
39 tree: &'a Tree<T>,
40 depth: usize,
41 current: Vec<NodeID>,
42 next: Vec<NodeID>,
43 next_index: usize,
44}
45
46
47impl<T: Clone> Tree<T> {
48 pub fn new() -> Self {
50 Self {
51 roots: vec![],
52 parents: vec![],
53 children: vec![],
54 data: vec![],
55 versions: vec![],
56 empty: Default::default()
57 }
58 }
59
60 pub fn is_valid(&self, node: NodeID) -> bool {
65 node.index < self.data.len() && !self.empty.contains(&node.index) && self.versions[node.index] == node.version
66 }
67
68
69 pub fn delete(&mut self, node: NodeID) -> usize {
73 if !self.is_valid(node) {
74 return 0;
75 }
76 let mut total = 1;
77 let ids = self.children_ids_unchecked(node).clone();
78 for child in ids {
79 total += self.delete(child);
80 }
81 if let Some(parent) = self.parents[node.index] {
82 if let Some(index) = self.children[parent.index].iter().position(|&x| x == node) {
83 self.children[parent.index].remove(index);
84 }
85 } else {
86 if let Some(index) = self.roots.iter().position(|&x| x == node) {
87 self.roots.remove(index);
88 }
89 }
90
91 self.data[node.index] = None;
92 self.parents[node.index] = None;
93 self.children[node.index].clear();
94 self.empty.insert(node.index);
95 total
96 }
97
98 pub fn add_root(&mut self, val: T) -> NodeID {
100 let i = NodeID{index: self.data.len(), version: 0};
101 self.data.push(Some(val));
102 self.roots.push(i);
103 self.children.push(vec![]);
104 self.parents.push(None);
105 self.versions.push(0);
106 i
107 }
108
109 pub fn get(&self, node: NodeID) -> Option<&T> {
111 match self.is_valid(node) {
112 true => self.data[node.index].as_ref(),
113 false => None,
114 }
115 }
116
117 pub fn get_mut(&mut self, node: NodeID) -> Option<&mut T> {
119 match self.is_valid(node) {
120 true => self.data[node.index].as_mut(),
121 false => None,
122 }
123 }
124
125 pub fn get_unchecked(&self, node: NodeID) -> &T {
127 self.data[node.index].as_ref().unwrap()
128 }
129
130 pub fn get_unchecked_mut(&mut self, node: NodeID) -> &mut T {
132 self.data[node.index].as_mut().unwrap()
133 }
134
135 pub fn set(&mut self, node: NodeID, val: T) {
137 if self.is_valid(node) {
138 self.data[node.index] = Some(val);
139 }
140 }
141
142 pub fn add_child(&mut self, node: NodeID, val: T) -> Option<NodeID> {
144 match self.is_valid(node) {
145 true => Some(self.add_child_unchecked(node, val)),
146 false => None
147 }
148 }
149
150 pub fn add_child_unchecked(&mut self, node: NodeID, val: T) -> NodeID {
153 let x = match self.empty.iter().next().cloned() {
154 Some(x) => {
155 self.data[x] = Some(val);
156 self.parents[x] = Some(node);
157 let version = self.versions.get_mut(x).unwrap();
158 *version += 1;
159 self.empty.remove(&x);
160 NodeID{ index: x, version: *version }
161 },
162 _ => {
163 self.data.push(Some(val));
164 self.parents.push(Some(node));
165 self.children.push(vec![]);
166 self.versions.push(0);
167 NodeID{index: self.data.len() - 1, version: 0 }
168 },
169 };
170 self.children[node.index].push(x);
171 x
172
173 }
174
175 pub fn children_ids_unchecked(&self, node: NodeID) -> &Vec<NodeID> {
178 &self.children[node.index]
179 }
180
181
182 pub fn root_ids(&self) -> &Vec<NodeID> {
184 &self.roots
185 }
186
187 pub fn parent_id(&self, node: NodeID) -> Option<NodeID> {
189 match self.is_valid(node) {
190 true => self.parents[node.index],
191 false => None,
192 }
193 }
194
195
196 pub fn iter_depth(&self) -> DepthIter<T> {
199 DepthIter{
200 tree: &self,
201 stacks: vec![IterStack{group: &self.roots, next_index: 0}],
202 }
203 }
204
205 pub fn iter_breadth(&self) -> BreadthIter<T> {
208 BreadthIter{
209 tree: &self,
210 current: self.roots.clone(),
211 next_index: 0,
212 next: vec![],
213 depth: 0,
214 }
215 }
216
217
218 pub fn path(&self, node: NodeID) -> Vec<NodeID> {
220 let mut path: Vec<NodeID> = vec![node];
221 let mut cur = node;
222 loop {
223 match self.parents[cur.index] {
224 Some(x) => {
225 path.push(x);
226 cur = x;
227 },
228 None => break,
229 }
230 }
231 path.reverse();
232 path
233 }
234
235 pub fn path_values_ref(&self, node: NodeID) -> Vec<&T> {
237 self.path(node).iter().map(|&x| self.get_unchecked(x)).collect::<Vec<_>>()
238 }
239
240 pub fn path_values(&self, node: NodeID) -> Vec<T> {
242 self
243 .path(node)
244 .into_iter()
245 .map(|x| self.get_unchecked(x).clone())
246 .collect()
247 }
248}
249
250
251#[derive(Debug, Eq, PartialEq)]
253pub struct Node<'a, T> {
254 pub id: NodeID,
255 pub value: &'a T,
256 pub depth: usize,
257}
258
259
260impl<'a, T: Clone> Iterator for DepthIter<'a, T> {
262 type Item = Node<'a, T>;
263
264 fn next(&mut self) -> Option<Self::Item> {
265 loop {
266 if self.stacks.is_empty(){
267 return None;
268 }
269 if {
270 let stack = self.stacks.last().unwrap();
271 stack.next_index >= stack.group.len()
272 }{
273 self.stacks.pop();
275 if self.stacks.is_empty() {
276 return None;
277 }
278 let stack = self.stacks.last_mut().unwrap();
279 stack.next_index += 1;
280 } else {
281 let depth = self.stacks.len() - 1;
284 let mut stack = self.stacks.last_mut().unwrap();
285 let node = stack.group[stack.next_index];
286 let children = self.tree.children_ids_unchecked(node);
287 if !children.is_empty() {
288 self.stacks.push(IterStack{
289 next_index: 0,
290 group: children,
291 })
292 } else {
293 stack.next_index += 1;
294 }
295 return Some(Self::Item {
296 id: node,
297 value: self.tree.get_unchecked(node),
298 depth,
299 });
300 }
301 }
302 }
303}
304
305
306
307impl<'a, T: Clone> Iterator for BreadthIter<'a, T> {
309 type Item = Node<'a, T>;
310 fn next(&mut self) -> Option<Self::Item> {
311 loop {
312 if self.current.is_empty() {
313 return None;
314 }
315 if self.next_index >= self.current.len() {
316 self.next_index = 0;
317 self.current = self.next.clone();
318 self.next.clear();
319 self.depth += 1;
320 continue;
321 }
322
323 let node = self.current[self.next_index];
324 let children = self.tree.children_ids_unchecked(node);
325 self.next.append(&mut children.clone());
326 self.next_index += 1;
327
328 return Some(Self::Item{
329 value: self.tree.get_unchecked(node),
330 depth: self.depth,
331 id: node,
332 });
333 }
334 }
335}
336
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 #[test]
343 fn depth_first_iteration() {
344 let mut tree: Tree<i32> = Tree::new();
345 let root = tree.add_root(0);
346 let child1 = tree.add_child_unchecked(root, 1);
347 let _child2 = tree.add_child_unchecked(root, 2);
348 let _child1_1 = tree.add_child_unchecked(child1, 11);
349
350 let expected: Vec<(i32, usize)> = vec![(0, 0), (1, 1), (11, 2), (2, 1)];
351 let real = tree.iter_depth().map(|x|{
352 (*x.value, x.depth)
353 }).collect::<Vec<_>>();
354 assert_eq!(real, expected);
355 }
356
357 #[test]
358 fn breadth_first_iteration() {
359 let mut tree: Tree<i32> = Tree::new();
360 let root = tree.add_root(0);
361 let child1 = tree.add_child_unchecked(root, 1);
362 let _child2 = tree.add_child_unchecked(root, 2);
363 let _child1_1 = tree.add_child_unchecked(child1, 11);
364
365 let expected: Vec<(i32, usize)> = vec![(0, 0), (1, 1), (2, 1), (11, 2)];
366 let real = tree.iter_breadth().map(|x|{
367 (*x.value, x.depth)
368 }).collect::<Vec<_>>();
369 assert_eq!(real, expected);
370 }
371}