1use crate::Tree;
2
3pub struct DfIter<'a,T>{
5 pub (in crate) stack : Vec<&'a Tree<T>>
6}
7
8pub struct DfIterMut<'a,T>{
10 pub (in crate) stack : Vec<&'a mut Tree<T>>
11}
12
13impl<'a,T> DfIter<'a,T> {
14 pub fn depth(self) -> DfDepthIter<'a,T>{
16 let mut s = self;
17 DfDepthIter {
18 stack : vec![(0,s.stack.pop().unwrap())]
19 }
20 }
21}
22
23impl<'a,T> DfIterMut<'a,T>{
24 pub fn depth(self) -> DfDepthIterMut<'a,T> {
26 let mut s = self;
27 DfDepthIterMut {
28 stack: vec![(0,s.stack.pop().unwrap())],
29 }
30 }
31}
32
33impl<'a,T> Iterator for DfIter<'a,T>{
34 type Item = &'a T;
35
36 fn next(&mut self) -> Option<Self::Item> {
37 if let Some(top) = self.stack.pop() {
38 for child in top.children.iter().rev() {
39 self.stack.push(child);
40 }
41 Some(&top.data)
42 }else{
43 Option::None
44 }
45 }
46}
47
48impl<'a,T> Iterator for DfIterMut<'a,T>{
49 type Item = &'a mut T;
50
51 fn next(&mut self) -> Option<Self::Item> {
52 if let Some(top) = self.stack.pop() {
53 for child in top.children.iter_mut().rev() {
54 self.stack.push(child);
55 }
56 Some(&mut top.data)
57 }else{
58 Option::None
59 }
60 }
61}
62
63pub struct DfDepthIter<'a,T> {
65 stack : Vec<(usize,&'a Tree<T>)>
66}
67
68pub struct DfDepthIterMut<'a,T> {
70 stack : Vec<(usize,&'a mut Tree<T>)>
71}
72
73impl<'a,T> Iterator for DfDepthIter<'a,T> {
74 type Item = (usize,&'a T);
75
76 fn next(&mut self) -> Option<Self::Item> {
77 if let Some((dpth,top)) = self.stack.pop() {
78 for child in top.children.iter().rev() {
79 self.stack.push((dpth + 1,child));
80 }
81 Some((dpth,&top.data))
82 }else{
83 Option::None
84 }
85 }
86}
87
88impl<'a,T> Iterator for DfDepthIterMut<'a,T> {
89 type Item = (usize,&'a mut T);
90
91 fn next(&mut self) -> Option<Self::Item> {
92 if let Some((dpth,top)) = self.stack.pop() {
93 for child in top.children.iter_mut().rev() {
94 self.stack.push((dpth + 1,child));
95 }
96 Some((dpth,&mut top.data))
97 }else{
98 Option::None
99 }
100 }
101}
102
103