Problem 419985 · easy · Level 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

       4
      / \
     2   6
    / \   \
   4   1   6
    \
     7

Input:  root = build_tree([4, 2, 6, 4, 1, None, 6, None, 7])
Output: 5
Explanation: 4 (root), 6, the lower 6 (equal to its parent), the lower 4 (equal to the root) and 7.

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

Input:  root = build_tree([5, 1, None, 2])
Output: 1
Explanation: 2 beats its parent 1 but not the root 5, so only the root is dominant.

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…