Count Good Nodes in Binary Tree Visualizer & Step-by-Step Algorithm Solution

Count the number of 'good' nodes in a binary tree (a node X is good if on the path from root to X there are no nodes with value greater than X).

Category: trees | Difficulty: Medium

Tags: DFS, Binary Tree, Recursion, Path Maximum, Tree Traversal

Count Good Nodes in Binary Tree

3
1
3
4
1
5
100%
state
goodNodesCount0
maxSoFar3
Initialization
1/27
Explanation

Start goodNodes on binary tree with root: Node(3).

Source Code
1function goodNodes(root) {
2 let count = 0;
3 function dfs(node, maxVal) {
4 if (!node) return;
5 if (node.val >= maxVal) count++;
6 const nextMax = Math.max(maxVal, node.val);
7 dfs(node.left, nextMax);
8 dfs(node.right, nextMax);
9 }
10 dfs(root, root.val);
11 return count;
12}