 All Problems
Count Good Nodes in Binary Tree
medium
tree
depth-first search
breadth-first search
binary tree
google

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

Example 1:

Input:  3 1 4 3 null 1 5
Output: 4

(Good nodes: 3 (root), 4, 3 (left child of 1), 5)

Example 2:

Input:  3 3 null 4 2
Output: 3

Constraints:

  • The number of nodes in the binary tree is in the range [1, 10⁵]
  • Each node's value is between [-10, 10]

Input format: BFS level-order, space-separated, null for missing nodes.

Output format: Integer — the count of good nodes.

Run to check your code against the sample cases, or submit to run every case