Count Good Nodes in Binary Tree

MediumTree recursionLeetCode 1448 ↗World 3-11
0:00 / 0:00

A node is good if nothing on the path from the root is bigger. Walk down with DFS carrying the largest value seen so far, and count every node that meets or beats it, in O(n) time.

▼

The problem

LeetCode 1448 (Medium). Given the root of a binary tree, a node X is *good* if no node on the path from the root to X has a value greater than X. Return the number of good nodes.

Example (LeetCode's example 1, on screen in scenes 2, 3, 4, 5 and 7): [3,1,4,3,null,1,5] → 4 (the root 3, the 3 under the 1, the 4 and the 5).

TRY IT ON LEETCODE ▶

The solution

def goodNodes(root):
    def dfs(node, best):     # best: path max
        if not node:
            return 0
        good = 1 if node.val >= best else 0
        best = max(best, node.val)
        return good + dfs(node.left, best) + dfs(node.right, best)
    return dfs(root, root.val)

Transcript

Count Good Nodes in Binary Tree. A node is good if nothing on the path from the root down to it is bigger. Count the good nodes. Here, each node is a signal tower, as tall as its value, and a good tower lights its fire.

Take this tree: three at the root, then one and four, then three, one and five. The root is always good: nothing sits above it. The lower three ties the root, and a tie still counts. Four and five are good too. Both ones sit below a three, so they stay dark. The answer is four.

The naive way checks each node on its own, climbing back up its whole path. Here, that's eight checks. But on a long chain, each path is one longer than the last, so the work grows like n squared.

The key idea: you never need the whole path, only its tallest tower. So walk down once, carrying that maximum like a flag. If a node is at least the flag, it's good. Then raise the flag to the larger value, and hand it to both children.

Let's walk it. The root, three, is good; the flag reads three. Go left: one is smaller, so not good. Its child, three, ties the flag: good. Back at the root, the flag is still three. Go right: four beats three, so it's good, and the flag rises to four. Below it, one is smaller: not good. Five beats four: good. Four good nodes.

In code, a depth-first helper takes a node and the max so far. An empty spot counts zero. The node adds one if it's at least the max. Then the max becomes the larger of the two, and we add both children's counts. Start at the root, with its own value.

Each node is visited once, so the time is order n. The recursion goes as deep as the tree is tall, so the space is order h.

Carry the max, compare, pass it down. That's Count Good Nodes in Binary Tree.