Count Good Nodes in Binary Tree [Medium]

20 Sep 2026 2 min read
2
The Count Good Nodes in Binary Tree problem requires counting the nodes in a binary tree that are considered good based on the values of their ancestors.

Problem

Given the root of a binary tree, a node is called good if there is no node on the path from the root to that node with a value greater than the node's value.

Return the number of good nodes in the binary tree.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
root:
       3
      / \
     1   4
    /   / \
   3   1   5
Output
4

Example 2

Input
root:
       3
      / \
     3   4
    / \   \
   2   4   5
Output
4

Solution

This solution uses Depth-First Search (DFS). We pass the maximum value encountered on the path from the root to the current node.

A node is a good node if its value is greater than or equal to the maximum value seen before reaching that node. We calculate newMaxValue using the current node's value and pass it to both subtrees.
class Solution {
    public int goodNodes(TreeNode root) {
        return dfs(root, root.val);
    }

    private int dfs(TreeNode node, int maxValue) {
        if (node == null) {
            return 0;
        }

        int newMaxValue = Math.max(maxValue, node.val);
        return (node.val >= maxValue ? 1 : 0)
                + dfs(node.left, newMaxValue)
                + dfs(node.right, newMaxValue);
    }
}

Complexity

Each node is visited exactly once, so the time complexity is O(n), where n is the number of nodes in the binary tree.

The DFS recursion uses space proportional to the height of the tree, so the extra space complexity is O(h), where h is the height of the tree.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion