-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110-balanced-binary-tree.js
More file actions
78 lines (64 loc) · 1.9 KB
/
110-balanced-binary-tree.js
File metadata and controls
78 lines (64 loc) · 1.9 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* 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) {
console.log("-".repeat(100));
function getNodeHeight(node, side) {
// console.log("node", node, "side", side);
if (node === null) {
return 0;
}
const lh = getNodeHeight(node.left);
const rh = getNodeHeight(node.right);
// en caso cada nodo por su cuenta sea desbalanceado.
if (lh === -1 || rh === -1) {
return -1;
}
if (Math.abs(lh - rh) > 1) {
return -1;
}
console.log("resultado", 1 + Math.max(lh, rh));
return 1 + Math.max(lh, rh);
}
// console.log("root", root);
if (root === null) {
return true;
}
return getNodeHeight(root) !== -1;
};
// Leetcode dice que un arbol binario es balanceado cuando
// la altura de su rama izquierda **PARA CADA NODO** es no mayor que uno de la altura de su rama derecha
// la altura de una rama es la distancia desde el nodo hasta el ultimo
// nodo de su lado izq o derecho sin hijos (o sea una hoja).
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
// Case 1
// Input: root = [3,9,20,null,null,15,7]
// Output: true
const l = new TreeNode(9);
const rl = new TreeNode(15);
const rr = new TreeNode(7);
const r = new TreeNode(20, rl, rr);
const root = new TreeNode();
// Failing case
// Input: root = [1,null,2,null,3]
// Output: false
// const rr = new TreeNode(3);
// const r = new TreeNode(2, null, rr);
// const root = new TreeNode(1, undefined, r);
// Failing case
// [1,2,2,3,null,null,3,4,null,null,4]
// false
console.log(isBalanced(root));