#1448

Count Good Nodes in Binary Tree

Medium DFS carrying the path maximum

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A node is "good" if no node on the path from the root to it has a greater value. Count the good nodes.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: nodes with no bigger node above them on their path.

Why this works: pass the maximum seen so far down the recursion.

Example: 3 (1 (3), 4 (1, 5))

good: 3, 3 (path 3,1,3), 4, 5 → 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a shared variable for the maximum and not restoring it when returning from a subtree.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon