Count Good Nodes in Binary Tree, explained

A node is good when no node on the path from the root down to it holds a larger value. Count them with a depth-first search that carries the largest value seen so far: a node is good if its value is at least that maximum, and its children receive the larger of the two. Each node is visited once, so the count takes O(n) time and memory proportional to the tree's height.

By Published 7 min read

What makes a node good

Take any node and look at the path that leads to it from the root, including the root and excluding nothing in between. The node is good if none of those earlier nodes has a value strictly greater than its own. Return how many good nodes the tree has. Values can be negative, and equal values do not disqualify a node.

          4
         / \
        2   6
       / \   \
      5   1   6
A tree drawn for this page. Four nodes are good: 4, 5, 6 and the lower 6.

Walk through it. The root 4 is good because nothing is above it. 2 is below 4, so it is not good. 5 has 4 and 2 above it, and 5 beats both, so it is good. 1 is not. The right child 6 beats 4. The lower 6 ties the 6 above it, and ties count, so it is good too. A tree of all negative values works the same way: for -3 with children -5 and -1, the root and -1 are good, for a total of two.

Why this is a useful problem

Most early tree problems return something up from the children, such as a height or a boolean. This one sends information the other way: each node needs a fact about its ancestors. Interviewers use it to see whether you recognize that pattern and carry a single number down instead of rebuilding the path. It is also a gentle place to show both recursive and iterative styles. The "look at everything above you" framing appears again in problems like Validate Binary Search Tree, which carries two bounds down instead of one maximum.

First attempt: keep the path and rescan it

Depth-first search naturally maintains the current root-to-node path if you push a value when entering a node and pop it when leaving. At each node, compare its value with the maximum of the whole path. That is correct, but finding the maximum scans up to h values at every node, for O(n × h) time: fine for a balanced tree, quadratic for a chain.

def count_unbeaten_slow(root):
    count = 0
    def visit(node, path):
        nonlocal count
        if node is None:
            return
        path.append(node.val)
        if node.val >= max(path):  # rescans the whole path every time
            count += 1
        visit(node.left, path)
        visit(node.right, path)
        path.pop()
    visit(root, [])
    return count
Rescanning the path at every node. O(n × h). Nodes have val, left and right.

Carry the maximum instead of the path

Only one fact about the path matters: its largest value. So pass that number down instead of the path. When you visit a node, it is good if its value is at least the number you were given. Its children get the larger of that number and the node's own value. Starting the root with its own value makes the root good automatically, without a special case or a minus infinity constant.

def count_unbeaten(root):
    if root is None:
        return 0
    count = 0
    stack = [(root, root.val)]  # node, largest value above it so far
    while stack:
        node, high = stack.pop()
        if node.val >= high:
            count += 1
            high = node.val
        for child in (node.left, node.right):
            if child:
                stack.append((child, high))
    return count
Python: iterative depth-first search with (node, highest so far) pairs. O(n) time, O(h) stack.
#include <algorithm>

struct TreeNode {
    int val;
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
    explicit TreeNode(int v) : val(v) {}
};

int countFrom(const TreeNode* node, int highest) {
    if (node == nullptr) return 0;
    int here = node->val >= highest ? 1 : 0;
    int next = std::max(highest, node->val);
    return here + countFrom(node->left, next) + countFrom(node->right, next);
}

int countUnbeaten(const TreeNode* root) {
    return root == nullptr ? 0 : countFrom(root, root->val);
}
C++: the recursive form, returning the count for each subtree.

The Python version uses an explicit stack so a very deep tree cannot hit the recursion limit. Each stack entry carries its own copy of the maximum, which is what makes the iterative version correct: sibling subtrees never see each other's values. The C++ version shows the recursive shape, where the count for a subtree is this node's contribution plus the counts from both children. A breadth-first search with the same pairs in a queue works equally well, since each node only needs its own path's maximum.

Complexity

n nodes, height h
ApproachTimeExtra space
Keep the path and rescan itO(n × h)O(h)
Pass the maximum down, recursiveO(n)O(h) recursion
Pass the maximum down, explicit stackO(n)O(h), at most one waiting sibling per level
Pass the maximum down, breadth-firstO(n)O(w) for the widest level
n nodes, height h. Scroll sideways on a small screen.

Cases to run

  • Single node: 1.
  • All values equal: every node is good.
  • Strictly decreasing chain from the root: only the root.
  • Strictly increasing chain: every node.
  • Negative values, where a starting maximum of 0 would be a bug.

Mistakes people make

  • Comparing each node only with its parent, which misses larger values further up.
  • Using strictly greater than, so ties are not counted.
  • Starting the maximum at 0, which wrongly rejects a negative root and its negative descendants.
  • Sharing one maximum variable across the whole search, so values from a left subtree leak into the right subtree.

Follow-ups

  • Return the good nodes, not just a count. Append the node instead of incrementing.
  • Good means strictly larger than everything above. Change the comparison to strictly greater and handle the root explicitly.
  • Good relative to the minimum instead. Carry the smallest value down and flip the comparison.
  • Paths that need the whole history. If the rule needs more than one summary number, such as "no repeated values above", carry a set and remove values when backtracking.

Explaining your approach

Fictional example

How a candidate might put it
Candidate
Each node needs to know the largest value above it. That's the only fact about the path that matters, so I'll pass it down.
Candidate
A node is good if its value is at least that number. Its children get the max of the two. I start the root with its own value so it counts.
Candidate
One visit per node, so O(n). I'll use an explicit stack with pairs, which keeps each branch's maximum separate and avoids recursion limits.

Validate Binary Search Tree passes two bounds down in the same way. Binary Tree Right Side View passes depth down, while Diameter of Binary Tree sends heights up. See them all on the coding problems hub.

Rehearsing with Natively

On Mac or Windows, Natively can read this problem and its tree from a screenshot as you practice, then suggest passing the maximum down and flag the tie and negative-value cases. It transcribes your mock session too, which makes it easy to see later whether you explained why siblings never share a maximum. The coding interview assistant page has more.

Questions people ask

How do you count good nodes in a binary tree?

Run a depth-first search that carries the largest value on the path so far. A node is good if its value is at least that maximum; its children receive the larger of the two. Start the root with its own value. It takes O(n) time.

Do equal values count as good nodes?

Yes. A node is good when no node above it is strictly greater, so a node that ties the path maximum is good.

What is the space complexity of Count Good Nodes?

O(h), the height of the tree, for the recursion or the explicit stack. That is O(log n) for a balanced tree and O(n) for a chain.

Why not start the maximum at zero?

Values can be negative. Starting at zero would mark a negative root and its negative descendants as not good. Start with the root's own value or with negative infinity.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP