CodingNodes / Trees / Count Good Nodes In Binary Tree System design Space play · ←→ step · R restart

Problem

In a binary tree, call a node good if no node on the path from the root down to it has a larger value. The root is always good, and a node equal to the biggest value above it still counts.

Given the root, return how many good nodes the tree has. The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 100000
  • -10000 ≤ Node.val ≤ 10000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is visited exactly once, and each visit does one comparison.

Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

A node is good if it is at least as big as every ancestor, which is the same as at least the maximum on its path. So pass that maximum down: start with the root's value, compare each node with it, and hand the larger of the two to the children. A node's count is itself (1 or 0) plus the counts of its two subtrees.