-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path110. Balanced Binary Tree.js
57 lines (57 loc) · 1.34 KB
/
110. 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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
/*
Solution 1 - O(N*N) looks
---------------------------
var isBalanced = function(root) {
if(!root) {
return true ;
}
function dfs(root) {
if (!root) {
return 0 ;
}
return Math.max(dfs(root.left), dfs(root.right)) + 1;
}
if(Math.abs(dfs(root.left) - dfs(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
};
*/
var isBalanced = function(root) {
if(!root) {
return true ;
}
function dfs(root) {
if (!root) {
return 0 ;
}
leftHeight = dfs(root.left);
rightHeight = dfs(root.right);
balanceFactor = Math.abs (leftHeight - rightHeight);
if (balanceFactor > 1 || leftHeight == -1 || rightHeight == -1) {return -1;}
return 1 + Math.max(leftHeight, rightHeight) ;
}
return dfs(root) != -1;
};