← Whiteboard questions

Count Good Nodes in Binary Tree

Count the nodes that no ancestor beats

DSA, Medium, Trees

Which structure or algorithm, and what does it cost.

You get a binary tree tree. Your code may take the root node or the list. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use a level-order list. It holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. An empty list is an empty tree. A node is good when nothing above it, on its path from the root, is larger. The root is always good. Return the number of good nodes.

Examples

Input tree = [6, 4, 8, 5, 2, 8, null, null, null, null, 9]
Output 4
Why the good nodes are the root 6, the node 8, the lower 8, and 9, which is larger than 6, 4 and 2 above it.
Input tree = [4, 4, null, 6, 1]
Output 3
Why a value equal to the largest above it is still good, so the second 4 counts. Node 6 counts. Node 1 does not.
Input tree = [3, 1, null, 5, null, 4]
Output 2
Why 4 beats the root 3, but 5 sits above it, so 4 is not good. Only the root 3 and the node 5 are good.

Constraints

Your answer must contain

Target Aim for O(n) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A node is good because of what lies above it. What do you need to know about the path from the root?

Hint 2 the approach

Looking up the whole path for each node repeats work. Could a node reuse what its parent already knows about the path above it?

Hint 3 the key step

Stack pairs of a node and the largest value above it. Count the node if it is at least that. Pass the larger of the two to its children.

Walkthrough

Full walkthrough brute force to best

Brute force

For every node, walk up through its ancestors to the root, and check that none is larger. A path can be as long as the tree is deep, so on a chain of n nodes the walks cost 1, 2, 3 and so on up to n. That is O(n^2) time.

Best method

A node is good when its value is at least the largest value on the path from the root. That largest value can be passed down: each child gets the larger of its parent's value and the value the parent received. Keep a stack of pairs, a node and the largest value above it. Start with the root, paired with its own value. Pop a pair. Count the node when its value is at least the pair's number. Push its children with the larger of the two numbers. Each node is handled once, so the work is linear and no walk up is needed.

Hand trace

Run on [6, 4, 8, 5, 2, 8, null, null, null, null, 9]. The tree: 6 has children 4 and 8. Node 4 has children 5 and 2. Node 8 has a left child 8. Node 2 has a right child 9. Stack [(6, 6)]. Pop 6: 6 is at least 6, good count 1. Push (4, 6) and (8, 6). Pop (8, 6): good, count 2. Push (8, 8). Pop (8, 8): good, count 3. Pop (4, 6): 4 is less than 6, not good. Push (5, 6) and (2, 6). Pop (2, 6): not good. Push (9, 6). Pop (9, 6): good, count 4. Pop (5, 6): not good. The answer is 4.

Code

def count_good_nodes(root):
    stack, good = [(root, root.val)] if root else [], 0
    while stack:
        node, top = stack.pop()
        if node.val >= top:
            good += 1
        top = max(top, node.val)
        stack.extend((child, top) for child in (node.left, node.right) if child)
    return good

Time and memory

O(n) time, because each node is pushed and popped once and costs one comparison. O(h) extra memory for the stack, with h the height of the tree. A chain gives O(n).

Common mistakes

  • Comparing a node only with its parent. In example 1, node 5 beats its parent 4 but not the root 6, so it is not good.
  • Counting only values that are strictly larger. A value equal to the largest above it is good, so use at least.
  • Passing the parent's value instead of the larger one. The number passed down must be the largest on the path, so take the maximum.

Related problems

More Trees problems
Count Good Nodes in Binary Tree: walkthrough and solution