-
Notifications
You must be signed in to change notification settings - Fork 279
/
Copy path110 Balanced Binary Tree.js
62 lines (49 loc) · 1.2 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
58
59
60
61
62
// Leetcode 110
// Language: Javascript
// Problem: https://leetcode.com/problems/balanced-binary-tree/
// Author: Chihung Yu
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var maxHeight = function(node){
if(node === null){
return 0;
}
return 1 + Math.max(maxHeight(node.left), maxHeight(node.right));
}
var minHeight = function(node){
if(node === null){
return 0;
}
return 1 + Math.min(minHeight(node.left), minHeight(node.right));
}
var height = function(node){
if(node === null){
return 0;
}
return 1 + Math.max(height(node.left), height(node.right));
}
var isBalanced = function(root) {
if(root === null){
return true;
}
// var maxh = maxHeight(root);
// var minh = minHeight(root);
// return Math.abs(maxh - minh) <= 1;
var lh = height(root.left);
var rh = height(root.right);
var diff = Math.abs(lh - rh);
if(diff <= 1){
return isBalanced(root.left) && isBalanced(root.right);
} else {
return false;
}
};