Count Good Nodes in Binary Tree

Difficulty: Medium

You're given the root of a binary tree. A node is good if no node on the path from the root to it has a greater value. In other words, its value is at least every value above it on that path. The root is always good.

Count the good nodes in the tree.

Examples

Input: root = [3,1,4,3,null,1,5]
Output: 4

The good nodes are the root (3), the 3 under the left 1, the 4, and the 5 — each is at least as large as everything above it on its path.

Input: root = [3,3,null,4,2]
Output: 3

3 (root), 3 (its child), and 4 are good. 2 is not, because 4 appeared earlier on its path.

Input: root = [1]
Output: 1

A single node with no ancestors is trivially good.

Constraints

  • The number of nodes is in the range [1, 10^5].

  • Each node's value is between -10^4 and 10^4.

Approach

Whether a node is good depends only on its ancestors, so work top-down. Walk down from the root, carrying the largest value seen on the current path. If a node's value is greater than or equal to it, the node is good and becomes the new maximum for its children.

Solutions

Recursive DFS (Top-Down)

Do a depth-first traversal, passing the path's maximum so far into each call. If a node's value is greater than or equal to it, count the node as good and pass its value down as the new maximum.

class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function goodNodes(root) {
  function dfs(node, maxSoFar) {
    if (node === null) return 0;

    let count = 0;
    if (node.val >= maxSoFar) {
      count = 1;
      maxSoFar = node.val;
    }

    return count + dfs(node.left, maxSoFar) + dfs(node.right, maxSoFar);
  }

  return dfs(root, -Infinity);
}

Time: O(n) · Space: O(h) — recursion stack, where h is the tree's height

Optimal — Iterative BFS

The same idea without recursion: use a queue where each entry holds a node and the maximum on the path to it. This avoids recursion-depth problems on very deep, skewed trees.

class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function goodNodes(root) {
  if (root === null) return 0;

  let count = 0;
  const queue = [[root, root.val]];

  while (queue.length > 0) {
    const [node, maxSoFar] = queue.shift();
    if (node.val >= maxSoFar) count++;

    const newMax = Math.max(maxSoFar, node.val);
    if (node.left !== null) queue.push([node.left, newMax]);
    if (node.right !== null) queue.push([node.right, newMax]);
  }

  return count;
}

Time: O(n) · Space: O(n) — the queue can hold an entire level's worth of nodes