Skip to content
Problem 1448 · LeetCode 1448(opens in a new tab)

Count Good Nodes in Binary Tree

MediumDepth-first search

You are given the root of a binary tree. Call a node good when no node on the way down from the root to it holds a larger value. Equal values are fine, and the root is always good.

Return how many good nodes the tree has.

Example 1

Input:  root = [5, 3, 8, 6, null, 2, 9]
Output: 4
Why:    5, 8, 6 and 9 are good; 3 and 2 have a bigger value above
2 more examples and the constraints

Example 2

Input:  root = [7, 7, 6, null, 7]
Output: 3
Why:    the three 7s are good, since a tie is allowed; 6 is not

Example 3

Input:  root = [-1, 5, -2, null, 4]
Output: 2
Why:    -1 and 5 are good; 4 sits below 5

Constraints

  • 1 ≤ number of nodes ≤ 100,000
  • −10,000 ≤ each node value ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recheck the whole pathO(n·h)
  2. DFS with the path maximumO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a chain of 100,000 nodesVerdict
Recheck the whole pathO(n·h)
Correct, slow on deep trees
DFS with the path maximumO(n)
Best; one number per node

n = number of nodes, h = height of the tree.

Edge cases to test

  • A single node. [42] has one good node: the root.
  • Ties. [3, 3, 3, 3, 3] has five good nodes, because an equal value above does not count against you.
  • Only falling values. A chain 5 → 4 → 3 → 2 has just one good node, the root.
  • Negative values. Do not start the max at 0: in [-1, 5, -2, null, 4] the root -1 must still be good.

Common mistakes

  • Starting the max at 0 instead of the root's value, so negative roots and their children are miscounted.
  • Using > instead of >=, so ties are wrongly ruled out.
  • Updating one shared max for the whole tree instead of passing it down each path, so a big value on the left leaks into the right side.

How to talk through it

  1. 1Clarify. Does an equal value above a node stop it from being good? Can values be negative?
  2. 2Give the brute force. Keep the path and compare each node with all of it; say it is O(n·h).
  3. 3Shrink the state. Only the largest value on the path matters, so pass one number down instead of a list.
  4. 4Code the walk. Push (node, max) pairs on a stack, count when the value is at least the max, and pass the new max to the children.
  5. 5Test out loud. Run the ties case and the negative-root case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?