Skip to content

Commit

Permalink
Merge pull request #1 from Granola-Team/fix/height-of-node
Browse files Browse the repository at this point in the history
rewrite Tree::height_of_node to not be recursive, + add inlining
  • Loading branch information
jenr24G authored Aug 22, 2023
2 parents 81319ca + 528aff4 commit df64e00
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/tree.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::cmp::Ordering;
use std::collections::VecDeque;

use super::snowflake::ProcessUniqueId;
use super::*;
Expand Down Expand Up @@ -200,20 +201,29 @@ impl<T> Tree<T> {
/// assert_eq!(2, tree.height());
/// ```
///
#[inline(always)]
pub fn height(&self) -> usize {
match self.root {
Some(ref id) => self.height_of_node(id),
_ => 0,
}
}

#[inline(always)]
fn height_of_node(&self, node: &NodeId) -> usize {
let mut h = 0;
for n in self.children_ids(node).unwrap() {
h = std::cmp::max(h, self.height_of_node(n));
let mut h = 1;
let mut to_process = VecDeque::new();

to_process.push_back((h, node));
while !to_process.is_empty() {
let (next_h, id) = to_process.pop_front().unwrap();
self.children_ids(id).unwrap().for_each(|child_id| {
to_process.push_back((next_h + 1, child_id));
h = std::cmp::max(h, next_h + 1);
});
}

h + 1
h
}

/// Inserts a new `Node` into the `Tree`. The `InsertBehavior` provided will determine where
Expand Down

0 comments on commit df64e00

Please sign in to comment.