Count Good Nodes in Binary Tree

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, call a node **good** if no node on the path from the root down to it (including the root) has a value strictly greater than the node's own value. In other words, a node is good when its value is at least the maximum seen on its root-to-node path. The root is always good. Return the number of good nodes in the tree. A single depth-first traversal that carries the running maximum is enough, giving O(n) time.

Examples

Input: root = [3,1,4,3,null,1,5]
Output: 4
Good nodes: the root 3, the 4, the 5, and the 3 under node 1 (path 3,1,3 has max 3).
Input: root = [3,3,null,4,2]
Output: 3
The 2 is not good because the path 3,3,2 contains larger values.
Input: root = [1]
Output: 1
The root alone is good.

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= Node.val <= 10^4
  • Values may repeat; a node equal to its path maximum is good

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems