InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Count Good Nodes in Binary Tree

medium Original ↗ 00:00

Problem

Given the root of a binary tree, call a node good if no node on the path from the root down to it has a value strictly greater than its own value. Equivalently, a node is good if it is greater than or equal to every node on its root-to-node path, itself included. Count the good nodes.

The root is always good: it has no ancestors.

Examples

Example 1

Input:  root = [3, 1, 4, 3, null, 1, 5]

            3
          /   \
         1     4
        /     / \
       3     1   5

Output: 4

Good nodes: 3 (root), 4 (path max so far is 3), 5 (path max 4), and the leaf 3 (path 3→1→3, max 3, and 3 >= 3). Both 1s fail because the root’s 3 exceeds them.

Example 2

Input:  root = [3, 3, null, 4, 2]

            3
           /
          3
         / \
        4   2
Output: 3

Good: root 3, the second 3 (ties count), and 4. The 2 fails because both 3s above it are larger.

Example 3

Input:  root = [7]
Output: 1

A single node is always good.

Constraints

  • Number of nodes is in [1, 10^5].
  • -10^4 <= Node.val <= 10^4
  • Expected complexity: O(n) time — a single traversal; O(h) extra space.

Think about it first

Hint 1 Whether a node is good depends on only one fact about its ancestors, not the full list. Which single number?
Hint 2 If you know the maximum value seen along the path so far, deciding whether the current node is good is one comparison. How does that maximum update as you step to a child?
Hint 3 DFS carrying `path_max` as a parameter: count the node if `node.val >= path_max`, then recurse into children with `max(path_max, node.val)`. An explicit stack of `(node, path_max)` pairs does the same iteratively.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug