From 528aff42741a50c92e802e822e1c1f31caa17a00 Mon Sep 17 00:00:00 2001 From: Jen Reiss Date: Tue, 22 Aug 2023 06:09:34 -0500 Subject: [PATCH] rewrite Tree::height_of_node to not be recursive, + add inlining --- src/tree.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/tree.rs b/src/tree.rs index 60dca61..828134d 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -1,4 +1,5 @@ use std::cmp::Ordering; +use std::collections::VecDeque; use super::snowflake::ProcessUniqueId; use super::*; @@ -200,6 +201,7 @@ impl Tree { /// assert_eq!(2, tree.height()); /// ``` /// + #[inline(always)] pub fn height(&self) -> usize { match self.root { Some(ref id) => self.height_of_node(id), @@ -207,13 +209,21 @@ impl Tree { } } + #[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