Skip to content

Commit f14ec57

Browse files
committed
more
1 parent e2b72fe commit f14ec57

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/sys/tree.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,10 @@ impl<'treeseq> LLTree<'treeseq> {
213213
pub fn parents(&self, u: NodeId) -> impl Iterator<Item = NodeId> + '_ {
214214
NodeIteratorAdapter(ParentsIterator::new(self, u))
215215
}
216+
217+
pub fn roots(&self) -> impl Iterator<Item = NodeId> + '_ {
218+
NodeIteratorAdapter(RootIterator::new(self))
219+
}
216220
}
217221

218222
// Trait defining iteration over nodes.
@@ -492,3 +496,39 @@ impl NodeIterator for ParentsIterator<'_> {
492496
self.current_node
493497
}
494498
}
499+
500+
struct RootIterator<'a> {
501+
current_root: Option<NodeId>,
502+
next_root: NodeId,
503+
tree: &'a LLTree<'a>,
504+
}
505+
506+
impl<'a> RootIterator<'a> {
507+
fn new(tree: &'a LLTree<'a>) -> Self {
508+
debug_assert!(tree.left_child(tree.virtual_root()).is_some());
509+
RootIterator {
510+
current_root: None,
511+
next_root: tree.left_child(tree.virtual_root()).unwrap_or(NodeId::NULL),
512+
tree,
513+
}
514+
}
515+
}
516+
517+
impl NodeIterator for RootIterator<'_> {
518+
fn next_node(&mut self) {
519+
self.current_root = match self.next_root {
520+
NodeId::NULL => None,
521+
r => {
522+
assert!(r >= 0);
523+
let cr = Some(r);
524+
debug_assert!(self.tree.right_sib(r).is_some());
525+
self.next_root = self.tree.right_sib(r).unwrap_or(NodeId::NULL);
526+
cr
527+
}
528+
};
529+
}
530+
531+
fn current_node(&mut self) -> Option<NodeId> {
532+
self.current_root
533+
}
534+
}

src/trees/tree.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,21 @@ impl<'treeseq> Tree<'treeseq> {
161161
self.inner.parent(u.into())
162162
}
163163

164+
/// Return an [`Iterator`] over the roots of the tree.
165+
///
166+
/// # Note
167+
///
168+
/// For a tree with multiple roots, the iteration starts
169+
/// at the left root.
170+
pub fn roots(&self) -> impl Iterator<Item = NodeId> + '_ {
171+
self.inner.roots()
172+
}
173+
174+
/// Return all roots as a vector.
175+
pub fn roots_to_vec(&self) -> Vec<NodeId> {
176+
self.roots().collect::<Vec::<_>>()
177+
}
178+
164179
/// Return an [`Iterator`] over all nodes in the tree.
165180
///
166181
/// # Parameters

0 commit comments

Comments
 (0)