-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0110-balanced-binary-tree.js
More file actions
33 lines (28 loc) · 918 Bytes
/
0110-balanced-binary-tree.js
File metadata and controls
33 lines (28 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Balanced Binary Tree
* Time Complexity: O(N)
* Space Complexity: O(H)
*/
var isBalanced = function (root) {
const calculateBalanceAndHeight = (currentPntr) => {
if (!currentPntr) {
return 0;
}
const heightLeftSubtree = calculateBalanceAndHeight(currentPntr.left);
if (heightLeftSubtree === -1) {
return -1;
}
const heightRightSubtree = calculateBalanceAndHeight(currentPntr.right);
if (heightRightSubtree === -1) {
return -1;
}
const heightDifference = Math.abs(heightLeftSubtree - heightRightSubtree);
if (heightDifference > 1) {
return -1;
}
const maximumHeight = 1 + Math.max(heightLeftSubtree, heightRightSubtree);
return maximumHeight;
};
const finalCheckResult = calculateBalanceAndHeight(root);
return finalCheckResult !== -1;
};