Count Good Nodes in Binary Tree

Count the nodes in a binary tree that have no larger value anywhere on the path above them.

Given the root of a binary tree, count its good nodes. A node is good when no node on the path from the root down to it has a larger value. An equal value above it does not stop it from being good.

Example 1
Input: root = [3, 1, 4, 3, null, 1, 5]
Output: 4
Explanation: the root 3, the 4, the 3 under 1, and the 5 are good.
Example 2
Input: root = [3, 3, null, 4, 2]
Output: 3
Explanation: the 3 under the root is good, because the value above it is equal, not larger.
Solution

The Idea

Picture yourself walking from the top of the tree down to one node, reading every value you pass. The node is good if none of the values you read was bigger than its own.

The input list of Example 1, [3, 1, 4, 3, null, 1, 5], reads the tree row by row. The root is 3, the next row holds its two children, 1 and 4, and the row after that holds their children. The null means 1 has no right child, so 1 has one child, a 3, and 4 has two, 1 and 5.

The root has nothing above it, so it is good. The 1 below it is not, because 3 is bigger. The 3 under that 1 is good: the path down to it reads 3, then 1, and neither is bigger than 3. Example 2 adds a tie: its second 3 sits right under the root 3, which is equal, so that 3 is good.

Walking back up the whole path for every node would read the same values again and again: the 1 and the 5 at the bottom right both look at 3 and 4. What does a node really need to know about the path above it? Only the largest value on it. A node is good exactly when its value is at least that largest value.

That largest value is also easy to carry downwards. A child's largest value above is the larger of two numbers: its parent's value, and the largest value above the parent. Look at the picture below.

The tree of Example 1. Each line between a parent and a child carries the largest value on the path so far: 3 from the root to 1 and to 4, 3 from 1 to its child 3, and 4 from 4 to its children 1 and 5. The root 3, the 4, the 3 under 1, and the 5 are good; both 1s are not good.

Each small blue box on a line holds the largest value on the path so far, passed down to the child. The root hands 3 to both children. On the left, 1 is smaller than 3, so it is marked not good, and it passes 3 on unchanged. The 3 below it ties that 3 and is good.

On the right, 4 is bigger than 3, so it is good and passes 4 down. Its child 1 is smaller than 4 and not good, while 5 is bigger and good. Four nodes are marked good, which is the answer of Example 1.

Solution Approach

Turning that idea into code means settling three things: how to visit every node while handing each one the largest value above it, what the root compares against, and how a tie is treated.

Visiting the nodes with recursion

How do we reach every node with the right largest value? A first thought is to list the path to each node and scan it. On a tree that is one long chain of n nodes, those paths hold 1, 2, up to n values, about n²/2 reads in all. Carrying the largest value down reads each node once.

A method count(node, maxAbove) handles one node, where maxAbove is the largest value on the path above that node. It decides whether the node is good, then calls itself on the left child and the right child, handing each the new largest value. A missing child, null, has no good nodes, and that ends each branch.

The walk goes all the way down the left branch before it comes back for the right one, which is called depth-first search. Each call gets its own copy of maxAbove, so a big value found on the left branch never reaches the right branch, and nothing has to be undone on the way back up.

The start value for the root

What should the root compare against, when nothing is above it? The root must come out good whatever its value, even a negative one. The call starts with Integer.MIN_VALUE, the smallest number a Java int can hold, -2,147,483,648, and every root value is at least that large.

Ties count as good

Should a node equal to the largest value above it count? Yes, because the rule only rules out a larger value above. So the test compares the node's value, node.val, with >=: node.val >= maxAbove. That is what makes the second 3 of Example 2 good.

Java Solution

The method goodNodes and its helper count work in these steps:

  1. First, goodNodes(root) starts the walk by calling count(root, Integer.MIN_VALUE), so the root has nothing larger above it.
  2. In count, when node is null, return 0, which ends that branch.
  3. Otherwise, compare the node's value with maxAbove: the variable good is 1 when node.val >= maxAbove, and 0 when it is smaller.
  4. Work out newMax, the larger of maxAbove and node.val. It is the largest value the node's children will have above them.
  5. Return good plus the counts from the left child and the right child, both called with newMax. The root's call adds up every node's 1 or 0, and that sum is the answer.

The class also has a small TreeNode class and a build helper that turns the row-by-row list, with null for a missing child, into a tree. The main method runs both examples, a single negative node, an all-negative tree, a tree whose values shrink downwards, and a chain going right whose values grow.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class CountGoodNodes {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static int goodNodes(TreeNode root) {
        return count(root, Integer.MIN_VALUE);
    }

    // maxAbove: the largest value on the path from the root down to node's parent
    private static int count(TreeNode node, int maxAbove) {
        if (node == null) {
            return 0;
        }
        int good = node.val >= maxAbove ? 1 : 0;     // nothing above is bigger
        int newMax = Math.max(maxAbove, node.val);   // what the children will see
        return good + count(node.left, newMax) + count(node.right, newMax);
    }

    // builds a tree from the row-by-row form, with null for a missing child
    static TreeNode build(Integer[] rows) {
        if (rows.length == 0 || rows[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(rows[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < rows.length) {
            TreeNode parent = parents.poll();
            if (rows[i] != null) {
                parent.left = new TreeNode(rows[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < rows.length && rows[i] != null) {
                parent.right = new TreeNode(rows[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    static void run(Integer... rows) {
        System.out.println(Arrays.toString(rows) + " -> " + goodNodes(build(rows)));
    }

    public static void main(String[] args) {
        run(3, 1, 4, 3, null, 1, 5);
        run(3, 3, null, 4, 2);
        run(-5);
        run(-1, -3, -2);
        run(5, 4, 3, 2, 1);
        run(1, null, 2, null, 3, null, 4);
    }
}

Running it prints:

Output
[3, 1, 4, 3, null, 1, 5] -> 4
[3, 3, null, 4, 2] -> 3
[-5] -> 1
[-1, -3, -2] -> 1
[5, 4, 3, 2, 1] -> 1
[1, null, 2, null, 3, null, 4] -> 4

Example 1 gives 4 and Example 2 gives 3, matching the expected answers. In Example 2, the 3 under the root counts only because of >=. With node.val > maxAbove instead, that tree gives 2.

The line [-5] -> 1 shows a negative root still counted as good, since -5 is larger than Integer.MIN_VALUE. Had the walk started from 0 instead, the same tree would give 0. In [-1, -3, -2], both children are smaller than the root -1, so only the root counts.

The tree [5, 4, 3, 2, 1] also gives 1: every value below 5 is smaller, so nothing but the root is good. The last line is the opposite case. Its four nodes form one chain of right children, 1, 2, 3, 4, each bigger than everything above it, so all four are good.

Complexity

The walk calls count once for each node and once for each missing child, and every call does a fixed, small amount of work.

  • Time: O(n), because count runs once for each of the n nodes and once for each of their n + 1 missing children, each call doing one comparison and one Math.max.
  • Space: O(h), because the recursion keeps one open call per node on the path down to the current node, and the tree's height h is the longest such path: about log n when balanced, n for a chain.

Carrying the smallest and largest values down the path is also how Maximum Difference Between Node and Ancestor works.