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
Output: 4
Explanation: the root 3, the 4, the 3 under 1, and the 5 are good.
Example 2
Output: 3
Explanation: the 3 under the root is good, because the value above it is equal, not larger.
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]null
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.
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)maxAbovenull
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
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_VALUEint
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>=node.val >= maxAbove
Java Solution
The method goodNodescount
- First,
starts the walk by callinggoodNodes(root) , so the root has nothing larger above it.count(root, Integer.MIN_VALUE) - In
, whencount isnode , return 0, which ends that branch.null - Otherwise, compare the node's value with
: the variablemaxAbove is 1 whengood , and 0 when it is smaller.node.val >= maxAbove - Work out
, the larger ofnewMax andmaxAbove . It is the largest value the node's children will have above them.node.val - Return
plus the counts from the left child and the right child, both called withgood . The root's call adds up every node's 1 or 0, and that sum is the answer.newMax
The class also has a small TreeNodebuildnullmain
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:
[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 >=node.val > maxAbove
The line [-5] -> 1Integer.MIN_VALUE[-1, -3, -2]
The tree [5, 4, 3, 2, 1]
Complexity
The walk calls count
- Time: O(n), because
runs once for each of the n nodes and once for each of their n + 1 missing children, each call doing one comparison and onecount .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