-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110BalancedBST.js
More file actions
40 lines (36 loc) · 1.17 KB
/
Copy path110BalancedBST.js
File metadata and controls
40 lines (36 loc) · 1.17 KB
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
/**
* 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}
*/
var isBalanced = function(root) {
const callDFS = (node) => {
if(!node) return true;
const left = callDFS(node.left); //height
const right = callDFS(node.right);//height
if(!left || !right || Math.abs(left - right) > 1) return false;
return Math.max(left,right) + 1; //Math.max in here returns which one has longer height
}
return callDFS(root);
};
//optimization
var isBalanced2 = function(root) {
let balanced = true;
const callDFS = (node) => {
if(!node) return true;
if(balanced == false) return; //optimization: early exit
const left = callDFS(node.left); //height
const right = callDFS(node.right);//height
if(!left || !right || Math.abs(left - right) > 1) balanced = false;
return Math.max(left,right) + 1; //Math.max in here returns which one has longer height
}
callDFS(root);
return balanced
};