Skip to the code
cf.
+50 XP

#351 Fewest Health Monitors

hard

Your frontend talks to a tree of microservices. A health monitor installed on a service watches that service, its parent, and its children. Every service must be watched by at least one monitor.

Write fewestMonitors(root) that returns the smallest number of monitors needed to watch every node of the tree. The tree has at least one node. Node values don't matter.

Example 1

Input: root = [0,0,null,0,0]
Output: 1

One monitor on the middle node watches its parent and both of its children.

Example 2

Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2

This chain of five needs two monitors, for example on the 2nd and 4th nodes.

Constraints

  • 1 <= number of services <= 1000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).