File tree Expand file tree Collapse file tree 2 files changed +23
-2
lines changed Expand file tree Collapse file tree 2 files changed +23
-2
lines changed Original file line number Diff line number Diff line change 11use std:: error:: Error ;
22
3- use rust_data_structures:: trees:: { TraversingOrder , BinarySearchTree } ;
3+ use rust_data_structures:: trees:: { BinarySearchTree } ;
44
55fn 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}
Original file line number Diff line number Diff 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 ;
You can’t perform that action at this time.
0 commit comments