Count Good Nodes in Binary Tree (LeetCode 1448): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

A node is good if no node on the path from the root down to it has a larger value. Count how many good nodes the binary tree contains. The root is always good.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Taken literally, the definition suggests a brute force: for every node, walk the path back to the root and check whether any ancestor is larger. Trees do not usually have parent pointers, and even with them, a skewed tree of n nodes makes that O(n²), since each node re-checks a long path.

Notice what you actually need from the path. You do not care about every ancestor, only about the largest one. A node is good exactly when its value is at least the maximum value seen on the way down. And that maximum is easy to maintain while walking down: the maximum for a child is just the maximum of the parent's running maximum and the parent's own value.

So do a depth-first traversal and pass the running maximum as a parameter. At each node, compare its value with the maximum it received. If it is at least as large, count it as good. Then update the maximum to include this node and pass the new value down to both children. Each subtree returns the number of good nodes it contains, and the parent adds them up.

This is the general pattern of pushing information from ancestors down into a recursion as a parameter, as opposed to bubbling results up through return values. Many path problems on trees reduce to it once you identify the one number the path needs to remember.

Approach: DFS with running path maximum

  1. Define dfs(node, maxVal). If node is None, return 0.
  2. Set res = 1 if node.val >= maxVal, otherwise 0.
  3. Update maxVal = max(maxVal, node.val) so children see the largest value on their path.
  4. Add dfs(node.left, maxVal) and dfs(node.right, maxVal) to res.
  5. Return res, and start the recursion with dfs(root, root.val).

Step-by-step example

root = [3,1,4,3,null,1,5]
  1. The root 3 is called with maxVal = 3. Since 3 ≥ 3 it is good. Its children receive maxVal = 3.
  2. Left child 1: 1 is less than 3, so it is not good. Its left child 3 receives maxVal = 3, and 3 ≥ 3, so it is good. This subtree contributes 1.
  3. Right child 4: 4 ≥ 3, so it is good, and its children receive maxVal = 4.
  4. Under 4, the node 1 is less than 4 and not good, while 5 ≥ 4 is good. This subtree contributes 2 including node 4.
  5. Total: 1 for the root, plus 1 from the left subtree, plus 2 from the right subtree, for 4 good nodes (3, 3, 4 and 5).

Code: Python, Java, C++

1class Solution:
2    def goodNodes(self, root: TreeNode) -> int:
3        def dfs(node, maxVal):
4            if not node:
5                return 0
6            
7            res = 1 if node.val >= maxVal else 0
8            maxVal = max(maxVal, node.val)
9            res += dfs(node.left, maxVal)
10            res += dfs(node.right, maxVal)
11            return res
12            
13        return dfs(root, root.val)

Time and space complexity

Time

O(n)

Every node is visited exactly once, with constant work per visit.

Space

O(h)

The recursion stack grows to the height h of the tree, which is O(log n) for a balanced tree and O(n) for a completely skewed one.

Other approaches

BFS with (node, max) pairs (time O(n), space O(n))

Run a level-order traversal where each queue entry holds a node together with the maximum on its path. The counting rule is the same. It avoids recursion depth limits on very deep trees.

Iterative DFS with an explicit stack (time O(n), space O(h))

Push (node, max) pairs onto a stack instead of recursing. It behaves like the recursive solution but is safe for degenerate trees that would overflow the call stack.

Common mistakes

  • Using > instead of >=. A node equal to the path maximum is still good, as with the second 3 in the example.
  • Updating the maximum before comparing, which makes every node trivially good.
  • Storing the maximum in a shared variable instead of a parameter, so a value from one branch leaks into its sibling branch.
  • Starting with a maximum of 0. Node values can be negative, so start with the root's value or negative infinity.

Frequently asked questions

What makes a node good in this problem?

A node is good if its value is greater than or equal to every value on the path from the root to it. That is the same as being at least the path's running maximum.

What is the time complexity of Count Good Nodes in Binary Tree?

It is O(n), since each node is visited once. Space is O(h) for the recursion stack, where h is the tree's height.

Can this be solved with BFS?

Yes. Store the path maximum alongside each node in the queue and apply the same check when you dequeue it. The result and the time complexity are the same.

Why pass the maximum as a parameter instead of using a global?

Each path has its own maximum. Passing it as a parameter gives every recursive call its own copy, so the left and right subtrees never see each other's values.