You get the root of a binary tree. Call a node good if no node on the path from the root down to it, the node itself included, holds a larger value. In other words, the node's value is at least the largest value above it.
Return the number of good nodes in the tree. The root is always good.
The good nodes are 6 (the root), 9 and 7. The path to 7 is 6 → 2 → 7, and nothing on it beats 7. The 6 under 9 and the 1 both have 9 above them, and 2 has 6 above it.
All three -1s are good: a value that ties the largest one above it still counts. -4 and -2 are not, because -1 sits above both.
Constraints
1 and 10⁵ nodes.-10⁴ <= Node.val <= 10⁴Whether a node is good depends only on the largest value on the path above it. Carry that maximum down as you walk the tree.
A node is good when nothing above it on its root path is bigger. Read literally, that asks you to look back up the path from every node, and on a tall, thin tree each look can cover tens of thousands of values.
Time O(n)Space O(h)
The full walkthrough and code are part of Premium
3