-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1448-Count-Good-Nodes-in-Binary-Tree.js
59 lines (46 loc) · 1.38 KB
/
1448-Count-Good-Nodes-in-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
/**
* https://leetcode.com/problems/count-good-nodes-in-binary-tree/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root, max = -Infinity, total = [ 0 ]) {
count(root, max, total);
return total[0]
};
const count = (root, max, total) => {
const isBaseCase = root === null;
if (isBaseCase) return 0;
return dfs(root, max, total);
}
const dfs = (root, max, total) => {
const isGood = max <= root.val
if (isGood) total[0]++;
max = Math.max(max, root.val);
count(root.left, max, total);
count(root.right, max, total);
}
/**
* https://leetcode.com/problems/count-good-nodes-in-binary-tree/
* Time O(N) | Space O(W)
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root, ) {
const isBaseCase = root === null;
if (isBaseCase) return 0
return bfs([[ root, -Infinity ]]);
}
const bfs = (queue, total = 0) => {
while (queue.length) {
for (let i = (queue.length - 1); 0 <= i; i--) {
let [ root, max ] = queue.shift();
const isGood = max <= root.val;
if (isGood) total++;
max = Math.max(max, root.val);
if (root.right) queue.push([ root.right, max ]);
if (root.left) queue.push([ root.left, max ]);
}
}
return total;
}