Skip to content

Commit 3b4023c

Browse files
committed
feat: add function for tree's height calculation to BinarySearchTree
1 parent 8f917ea commit 3b4023c

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/bin/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::error::Error;
22

3-
use rust_data_structures::trees::{TraversingOrder, BinarySearchTree};
3+
use rust_data_structures::trees::{BinarySearchTree};
44

55
fn main() -> Result<(), Box<dyn Error>> {
66
let mut tree = BinarySearchTree::new();
@@ -16,7 +16,7 @@ fn main() -> Result<(), Box<dyn Error>> {
1616
tree.insert(10);
1717
tree.insert(15);
1818

19-
tree.traverse(TraversingOrder::InOrder);
19+
println!("{}", tree.get_height());
2020

2121
Ok(())
2222
}

src/trees.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ impl<T: Ord + Display> BinarySearchTree<T> {
7272
}
7373
}
7474

75+
pub fn get_height(&self) -> i32 {
76+
Self::height(self.root.as_ref())
77+
}
78+
7579
fn traverse_pre_order(root: Option<&Rc<RefCell<Node<T>>>>) {
7680
if root.is_none() {
7781
return;
@@ -114,6 +118,23 @@ impl<T: Ord + Display> BinarySearchTree<T> {
114118
println!("{}", borrowed_root.value);
115119
}
116120

121+
fn height(root: Option<&Rc<RefCell<Node<T>>>>) -> i32 {
122+
if root.is_none() {
123+
return -1;
124+
}
125+
126+
let borrowed_root = root.unwrap().borrow();
127+
128+
if borrowed_root.left_child.is_none() && borrowed_root.right_child.is_none() {
129+
return 0;
130+
}
131+
132+
let left_subtree_height = Self::height(borrowed_root.left_child.as_ref());
133+
let right_subtree_height = Self::height(borrowed_root.right_child.as_ref());
134+
135+
1 + left_subtree_height.max(right_subtree_height)
136+
}
137+
117138
fn find_free_parent(&self, value: &T) -> OptionalNode<T> {
118139
if self.root.is_none() {
119140
return None;

0 commit comments

Comments
 (0)