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 Tree INPUT Binary Tree Structure 3 1 4 3 1 5 root = [3,1,4,3,null,1,5] 7 nodes total in tree ALGORITHM STEPS 1 Start DFS from root Track max value on path 2 Check each node If node.val >= pathMax: GOOD 3 Update path maximum pathMax = max(pathMax, val) 4 Recurse to children Sum good nodes count DFS Traversal Example Path to 3(root): max=3 [OK] Path to 1: max=3 [NOT GOOD] Path to 4: max=4 [OK] Path to 3(leaf): max=3 [OK] Path to 5: max=5 [OK] FINAL RESULT Good Nodes Highlighted 3 GOOD 1 4 GOOD 3 GOOD 1 5 GOOD Good Node Not Good Output: 4 Key Insight: A node is "good" if no ancestor has a greater value. By tracking the maximum value along the path during DFS traversal, we can determine in O(1) time if each node is good. Time: O(n), Space: O(h). TutorialsPoint - Count Good Nodes in Binary Tree | DFS with Path Maximum Approach
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