Skip to the code
cf.
+25 XP

#320 Nodes That Top Their Ancestors

medium

A notification panel is a tree of grouped alerts, and each alert has a priority. An alert is shown as a headline when no group above it (on the path from the root down to it) has a higher priority.

Write countHeadlines(root) that returns how many nodes have a value greater than or equal to every value on the path from the root to them. The root always counts. An empty tree returns 0.

Example 1

Input: root = [5,2,8,6,null,7,9]
Output: 4

5, 6 (the path above it is 5, 2), 8, and 9 count. 2 and 7 have a bigger value above them.

Example 2

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

3, the second 3 (equal counts), and 4. 2 is below a 3.

Constraints

  • 0 <= number of nodes <= 100000
  • -10000 <= priority <= 10000

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).