Skip to content
Decoder

Count Good Nodes in Binary Tree

Medium

Problem

Call a node good if, on the path from the root down to it, **no node has a larger value** than it. The root is always good.

Given the root of a binary tree, return how many good nodes it has.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[3, 1, 4, 3, null, 1, 5]
Output
4
Why
3, the lower 3, 4 and 5

Example 2

Input
[3, 3, null, 4, 2]
Output
3
Why
an equal value still counts as good

Example 3

Input
[1]
Output
1

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= Node.val <= 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.