Count Good Nodes in Binary Tree

mediumTreesDFS carrying max value along pathSolve on LeetCode#1448

Part of Practice: Levels & BST Rules

In a binary tree, call a node "good" if no node on the path from the root down to it has a value greater than its own. The root is always good (its path is just itself). Given the root, count how many good nodes the tree contains.

The tree has 1 to 100,000 nodes with values between -10,000 and 10,000. Ties count: a node equal to the maximum above it is still good.

Examples

Input:
root = [3,1,4,3,null,1,5]
Output:
4

Good nodes: the root 3; the 4 (path 3→4, nothing bigger); the 5 (path 3→4→5); and the leaf 3 (path 3→1→3, no ancestor exceeds 3). The 1s are blocked by the root's 3.

Input:
root = [3,3,null,4,2]
Output:
3

The root, the left child 3 (a tie still counts), and the 4. The 2 is blocked by the 3s above it on its path.

Input:
root = [1]
Output:
1

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.