Skip to content

Count Good Nodes in Binary Tree

Count the nodes that are at least as large as every value above them, passing the path maximum down.

MediumTree DFS and BST
Solve on LeetCode

The problem

You get the root of a non-empty binary tree. A node is good if no node on the path from the root down to it has a larger value. Return how many good nodes the tree has; the root is always good.

Input root = [6, 4, 9, 7, 2, 8, 10]

Output 4

6, 9, 7 and 10 are good. 4 and 2 sit below the larger 6, and 8 sits below 9.

Input root = [5, 5, 3, null, 5]

Output 3

All three 5s are good, because a value equal to the largest one above it still counts. 3 is below a 5, so it is not.

How to spot the pattern

  • Whether a node counts depends on the values on its path from the root.
  • One number, the largest value seen so far on the path, sums up everything you need to know about that path.

The idea

To judge a node you don't need the whole path above it, only the largest value on that path. So carry that maximum down as a parameter: a node is good when its value is at least the maximum, and its children receive the larger of the two. Each node is then checked once against a single number.

Brute force: For every node, walk back up to the root and compare it with each ancestor, which takes O(n * h) time.

Step by step

  1. 1Start a DFS at the root with best set to the root's value.
  2. 2At each node, count it as good if node.val >= best.
  3. 3Update best to max(best, node.val) before going to the children.
  4. 4Return this node's count plus the counts from its left and right subtrees.

See the pattern move

The tree dfs and bst pattern on a small example. Step through it, or press play.

Code

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def count(node: Optional[TreeNode], best: int) -> int:
            # best is the largest value on the path from the root down to node's parent.
            if node is None:
                return 0
            good = 1 if node.val >= best else 0
            best = max(best, node.val)
            return good + count(node.left, best) + count(node.right, best)

        return count(root, root.val)

Complexity

Time

O(n)

Space

O(h)

Each node is visited once with constant work; the recursion goes as deep as the tree's height h.

Watch out for

  • Using > instead of >=: a node equal to the largest value above it is still good.
  • Comparing a node only with its parent, when a bigger value further up the path also rules it out.
  • Starting best at 0, which breaks trees with negative values; start from the root's value instead.

Follow-up questions

Can you do it with BFS?

Yes. Put each node in the queue together with the largest value on its path, and hand the updated maximum to its children.

What if a node counts when it is larger than everything below it instead?

Flip the direction: compute each subtree's maximum bottom-up, and count a node when its value is larger than the maximum of both subtrees.

In Hinglish

Upar se neeche jaate hue ab tak ka sabse bada number saath le chalo. Node ki value usse kam nahi hai toh woh good hai; phir max update karke bachchon ko bhej do.

Related problems