forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0110-balanced-binary-tree.js
78 lines (59 loc) · 1.81 KB
/
0110-balanced-binary-tree.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* https://leetcode.com/problems/balanced-binary-tree/
* TIme O(N) | Space O(H)
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return true;
if (!isAcceptableHeight(root)) return false;
if (!isChildBalanced(root)) return false;
return true;
}
const isChildBalanced = (root) => {
const left = isBalanced(root.left);
const right = isBalanced(root.right);
return left && right
}
const isAcceptableHeight = (root) => {
const left = getHeight(root.left);
const right = getHeight(root.right);
const difference = Math.abs(left - right);
return difference <= 1;
}
const getHeight = (root) => {
const isBaseCase = root === null;
if (isBaseCase) return 0;
return dfs(root);
}
var dfs = (root) => {
const left = getHeight(root.left)
const right = getHeight(root.right);
const height = Math.max(left, right);
return height + 1;
}
/**
* https://leetcode.com/problems/balanced-binary-tree/
* TIme O(N) | Space O(H)
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function (root) {
const [ _height, _isBalanced ] = isRootBalanced(root);
return _isBalanced;
};
var isRootBalanced = (root) => {
const isBaseCase = root === null
if (isBaseCase) return [ -1, true ];
return dfs(root)
}
var dfs = (root) => {
const [ left, isLeftBalanced ] = isRootBalanced(root.left);
const [ right, isRightBalanced ] = isRootBalanced(root.right);
const [ height, difference ] = [ Math.max(left, right), Math.abs(left - right) ];
const isAcceptableHeight = difference <= 1;
const _isBalanced = isLeftBalanced && isRightBalanced;
const _isRootBalanced = _isBalanced && isAcceptableHeight;
return [ (height + 1), _isRootBalanced ];
}