TRT
Sign in
mediumCoreLeetCode#top-down recursion

Count good nodes in binary tree

Count nodes that are at least as large as every node on the path from the root, passing the running maximum down.

The Runtime Theory Team1 min read
Taught inTree recursion patternsPro — members onlyMost tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [3, 1, 4, 3, null, 1, 5]

out4

inroot = [3, 3, null, 4, 2]

out3

inroot = [1]

out1

A node is good if no node on the path from the root to it has a greater value. Return the number of good nodes.

Before you code

Whether a node is good depends on its ancestors, not its descendants, so the information must flow from the root down.

Hints

  1. Recurse with (node, max_so_far), starting with the root's value.
  2. The node is good if node.val >= max_so_far.
  3. Pass max(max_so_far, node.val) to both children and add up the counts.

Production & complexity notes

When solving Count good nodes in binary tree on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tree recursion patterns to reinforce the underlying pattern.

What it practices

Passing information down the tree, from Tree recursion patterns.

Not started

Sign in to save your learning progress.

Sign in to save