22 · Tree Recursion

#1448 Count Good Nodes in Binary Tree

Mediumsolve on LeetCode ↗

frequently reported atMicrosoftAmazonGoogle

the problem

In plain words

Call a node good if no node on the path from the root down to it has a bigger value. Count the good nodes. The root is always good.

in root = [3,1,4,3,null,1,5]

out 4

The root 3, then 4, 5 and the lower 3 are good; the two 1s are not.

in root = [3,3,null,4,2]

out 3

2 is not good: a 3 sits above it.

in root = [1]

out 1

  • 1 ≤ number of nodes ≤ 10⁵
  • -10⁴ ≤ Node.val ≤ 10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #129
      Sum Root to Leaf Numbers
      Mediumin Tree Recursion
    2. #112
      Path Sum
      Easyin Tree Recursion
    3. #98