Problem 400396 · easy · Level 04 Non-Linear Data Structures

Nodes Larger Than Their Parent

binary trees · traversal · parent tracking

In a family tree of pumpkin weights, every node holds a weight and a child is a grower if its weight is strictly larger than its parent's weight. Given the root, return how many growers the tree has. The root has no parent and is never a grower.

Examples

      5
     / \
    3   8
   / \   \
  6   1   8

Input:  root = build_tree([5, 3, 8, 6, 1, None, 8])
Output: 2
Explanation: 8 > 5 and 6 > 3. The leaf 8 equals its parent 8, so it does not count.
Input:  root = build_tree([7])
Output: 0

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Carry the parent's value through the traversal
  • Compare each child with its own parent only
  • Exclude the root, which has no parent
Starting Python…