File tree Expand file tree Collapse file tree 2 files changed +25
-1
lines changed Expand file tree Collapse file tree 2 files changed +25
-1
lines changed Original file line number Diff line number Diff line change @@ -161,6 +161,23 @@ class Tree {
161
161
}
162
162
}
163
163
164
+ checkIsBalanced ( currentNode = this . root ) {
165
+ if ( ! currentNode ) {
166
+ return true ;
167
+ }
168
+
169
+ const leftHeight = this . height ( currentNode . left ) ;
170
+ const rightHeight = this . height ( currentNode . right ) ;
171
+
172
+ const difference = Math . abs ( leftHeight - rightHeight ) ;
173
+
174
+ return (
175
+ difference <= 1
176
+ && this . checkIsBalanced ( currentNode . left )
177
+ && this . checkIsBalanced ( currentNode . right )
178
+ ) ;
179
+ }
180
+
164
181
print ( node = this . root , prefix = "" , isLeft = true ) {
165
182
if ( node === null ) {
166
183
return ;
Original file line number Diff line number Diff line change @@ -26,4 +26,11 @@ console.log(tree.inOrder());
26
26
const seven = tree . find ( 7 ) ;
27
27
28
28
console . log ( tree . height ( seven ) ) ;
29
- console . log ( tree . depth ( seven ) ) ;
29
+ console . log ( tree . depth ( seven ) ) ;
30
+
31
+ console . log ( tree . checkIsBalanced ( ) ) ;
32
+
33
+ tree . insert ( 2.5 ) ;
34
+ tree . print ( ) ;
35
+
36
+ console . log ( tree . checkIsBalanced ( ) ) ;
You can’t perform that action at this time.
0 commit comments