Skip to content

Commit 1dd93ad

Browse files
committed
feat: add checkIsBalanced method to BST
1 parent 8340407 commit 1dd93ad

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

binary_search_tree/Tree.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,23 @@ class Tree {
161161
}
162162
}
163163

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+
164181
print(node = this.root, prefix = "", isLeft = true) {
165182
if (node === null) {
166183
return;

binary_search_tree/index.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,11 @@ console.log(tree.inOrder());
2626
const seven = tree.find(7);
2727

2828
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());

0 commit comments

Comments
 (0)