Skip to content

Commit 00d015e

Browse files
committed
Create: 1448-Count-Good-Nodes-in-Binary-Tree.ts
1 parent 92d54b8 commit 00d015e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function goodNodes(root: TreeNode | null): number {
2+
// edge case
3+
if (root === null) return 0;
4+
5+
//keep track of the count
6+
let count = 0;
7+
8+
const dfs = (root, max) => {
9+
//if value is bigger than max of path, then it is a good node
10+
if (root.val >= max) count++;
11+
12+
//extend search to children if not null with updated max(takes current node in consideration too)
13+
if (root.left !== null) dfs(root.left, Math.max(max, root.val));
14+
if (root.right !== null) dfs(root.right, Math.max(max, root.val));
15+
};
16+
17+
//starts with negative max value, because min value is just the smaller positive value in javascript
18+
dfs(root, -Number.MAX_VALUE);
19+
20+
return count;
21+
}

0 commit comments

Comments
 (0)