-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode-110-balancedBinaryTree.js
87 lines (74 loc) · 2.18 KB
/
leetcode-110-balancedBinaryTree.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var isBalanced = function (root) {
if (!root) return true;
const left = countDepth(root.left);
const right = countDepth(root.right);
if (Math.abs(left - right) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
};
const countDepth = (root) => {
if (!root) return 0;
return 1 + Math.max(countDepth(root.left), countDepth(root.right));
};
/**
* 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}
*/
// [1,2,2,3,null,null,3,4,null,null,4]
// Output true
// Expected false
// var isBalanced = function (root) {
// if (!root) return true;
// let isBal = true;
// function dfs(node) {
// if (!node) return 0;
// const left = dfs(node.left);
// const right = dfs(node.right);
// if (Math.abs(left - right) > 1) isBal = false;
// return 1 + Math.max(left, right);
// }
// dfs(root);
// return isBal;
// };
// // chat
// var isBalanced = function (root) {
// if (!root) return true;
// function getHeight(node) {
// if (!node) return 0;
// return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
// }
// return (
// Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1 &&
// isBalanced(root.left) &&
// isBalanced(root.right)
// );
// };
// var isBalanced = function(root) {
// if (!root) return true;
// const stack = [root];
// while (stack.length > 0) {
// const c = stack.pop();
// const left = count(c.left);
// const right = count(c.right);
// if (!checkBalance(left,right)) return false;
// c.left && stack.push(c.left);
// c.right && stack.push(c.right);
// }
// return true;
// }
// const checkBalance = (left, right) => {
// return (right === left || right === left + 1 || left === right + 1)
// }
// var count = function(root) {
// if (!root) return 0;
// const left = 1 + count(root.left);
// const right = 1 + count(root.right);
// return Math.max(left, right);
// };