-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_247.js
58 lines (49 loc) Β· 1011 Bytes
/
problem_247.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
/**
* Definition for a binary tree node.
*/
function TreeNode(val) {
this.val = val;
this.left = null;
this.right = null;
}
/**
* Given a binary tree, determine whether or not it is height-balanced.
* Time Complexity: O(n)
* @param {TreeNode} root
* @return {boolean}
*/
function isHeightBalanced(root) {
const dfs = node => {
if (!node) return 0;
const left = 1 + dfs(node.left);
const right = 1 + dfs(node.right);
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right);
};
return dfs(root) !== -1;
}
const root = new TreeNode(3);
const a = new TreeNode(9);
const b = new TreeNode(20);
const c = new TreeNode(15);
const d = new TreeNode(7);
root.left = a;
root.right = b;
b.left = c;
b.right = d;
// 3
// / \
// 9 20
// / \
// 15 7
console.log(isHeightBalanced(root)); // true
const e = new TreeNode(30);
d.right = e;
// 3
// / \
// 9 20
// / \
// 15 7
// \
// 30
console.log(isHeightBalanced(root)); // false