Problem 419985 · easy · Phase 04 Non-Linear Data Structures

Nodes That Beat Every Ancestor

binary tree · recursion · depth-first search

A node is dominant when its value is greater than or equal to every value on the path from the root down to it (the root itself is always dominant). Return the number of dominant nodes in the tree.

Examples

      3
     / \
    1   4
   /   / \
  3   1   5

Input:  root = build_tree([3, 1, 4, 3, None, 1, 5])
Output: 4
Explanation: 3 (root), 4, 5 and the lower 3 (its ancestors are 3 and 1).

Input:  root = build_tree([3, 3, None, 4, 2])
Output: 3

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= node.val <= 1000

Goals

  • Carry the maximum value seen on the current root path
  • Count a node by comparing it with that running maximum
Starting Python…