AlgoInsight

DSA problem

Count Good Nodes in Binary Tree

MediumTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop600MicrosoftAmazonGoogleBloomberg

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

Equivalently, walk from the root toward any node X; if X.val is at least as large as every value seen along the way, then X is good. The root is always good (no ancestors to violate the rule). A leaf may or may not be good depending on the chain of values above it.

The natural algorithm carries the running maximum so far down the tree as recursion descends. When we enter a node we compare its value with the maximum seen on the path; if node.val >= maxSoFar we add 1 to the running count and update the maximum for the children. Otherwise we leave the maximum unchanged. We then recurse into both children with this (possibly updated) maximum.

Although the information flow is top-down (we push the maximum downward), the aggregation of the result happens as the recursion unwinds — each call sums up the counts from its two children plus its own contribution. That makes this a textbook hybrid traversal: an order-agnostic DFS structurally, with a top-down running parameter and a post-order aggregation. The whole tree is visited once, giving O(n) time and O(h) stack space.

Examples

Example 1
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: The good nodes are: root (3), 4 (the right child of the root), 5 (path 3→4→5 has max 4 ≤ 5), and the deeper 3 (path 3→1→3 has max 3 ≤ 3). Total = 4.
Example 2
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Good nodes: root (3), its left child (3), and the leaf 4 (path 3→3→4 has max 3 ≤ 4). The 2 is not good because 3 > 2 along the path.
Example 3
Input: root = [1]
Output: 1
Explanation: A single root is always good (no ancestors).

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems