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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code