-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced-binary-tree.js
56 lines (47 loc) · 1.22 KB
/
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
// https://www.interviewcake.com/question/javascript/balanced-binary-tree
function BinaryTreeNode(val) {
this.val = val;
this.left = this.right = null;
}
BinaryTreeNode.prototype.insertLeft = function(val) {
this.left = new BinaryTreeNode(val);
return this.left;
}
BinaryTreeNode.prototype.insertRight = function(val) {
this.right = new BinaryTreeNode(val);
return this.right;
}
function balancedBinaryTree(root) {
if (!root) return false;
let stack = [];
let depth = [];
stack.push([root, 0]);
while (stack.length !== 0) {
let item = stack.pop();
let node = item[0], d = item[1];
if (!node.left && !node.right) {
// leaf node
if (depth.indexOf(d) === -1) {
depth.push(d);
if (depth.length > 2 ||
depth.length === 2 && Math.abs(depth[0] - depth[1]) > 1) {
return false;
}
}
}
if (node.left) {
stack.push([node.left, d + 1]);
}
if (node.right) {
stack.push([node.right, d + 1]);
}
}
return true;
}
var a = new BinaryTreeNode('a');
var b = a.insertLeft('b');
var c = a.insertRight('c');
var d = b.insertLeft('d');
var e = b.insertRight('e');
var f = c.insertRight('f');
console.log(balancedBinaryTree(a));