Count Good Nodes in Binary Tree - Problem

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

Input & Output

Example 1 — Standard Binary Tree
$ Input: root = [3,1,4,3,null,1,5]
Output: 4
💡 Note: Good nodes are: 3 (root, no ancestors), 4 (path: 3→4, max=3, 4≥3), left leaf 3 (path: 3→1→3, max=3, 3≥3), and 5 (path: 3→4→5, max=4, 5≥4). Total = 4 good nodes.
Example 2 — All Values Same
$ Input: root = [3,3,null,4,2]
Output: 3
💡 Note: Good nodes are: 3 (root), left 3 (path: 3→3, max=3, 3≥3), and 4 (path: 3→3→4, max=3, 4≥3). Node 2 is not good since path 3→3→2 has max=3 and 2<3.
Example 3 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Only the root node exists. Root is always good since it has no ancestors to compare against.

Constraints

  • The number of nodes in the binary tree is in the range [1, 105].
  • Each node's value is between [-104, 104].

Visualization

Tap to expand
Count Good Nodes in Binary Tree314315Good Nodes (4 total):• Root 3: No ancestors• Node 4: Path max = 3, 4 ≥ 3 ✓• Left leaf 3: Path max = 3, 3 ≥ 3 ✓• Node 5: Path max = 4, 5 ≥ 4 ✓Bad Nodes:• Left node 1: Path max = 3, 1 < 3 ✗• Right leaf 1: Path max = 4, 1 < 4 ✗Algorithm Steps:1. DFS traversal from root2. Track path maximum3. Node is good if val ≥ path_max4. Count all good nodesTime: O(n), Space: O(h)
Understanding the Visualization
1
Input Tree
Binary tree with nodes having different values
2
Check Paths
For each node, compare with maximum value on path from root
3
Count Good
Count nodes where value >= path maximum
Key Takeaway
🎯 Key Insight: Track maximum value from root to current node during DFS - a node is good if its value is at least this maximum
Asked in
Amazon 45 Microsoft 32 Google 28 Facebook 25
125.0K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen