15% off all plans & roadmaps Use code

See plans

Count Good Nodes in Binary Tree

Updated

TL;DR: A node is good when no ancestor on its root-to-node path has a larger value. Walk the tree once in preorder, carry the largest value seen so far down each branch, and count a node when it ties or beats that value.

Problem

You are given the root of a binary tree. A node X is called good when no node on the path from the root to X has a value greater than X. The path includes both the root and X itself, so the root of a non-empty tree is always good.

Return the number of good nodes in the tree. A missing child is not a node, and an empty tree has zero good nodes.

Example 1

Input: root = [6,2,9,null,4,7,11]
Output: 3
Explanation: The root 6 is good, and so are 9 and 11. Every other node has a larger value somewhere above it on its path.

Example 2

Input: root = [5,8,3,7,null,null,4]
Output: 2
Explanation: The root 5 and node 8 are good. Node 7 sits below the larger value 8. Nodes 3 and 4 sit below the larger value 5.

Example 3

Input: root = []
Output: 0
Explanation: The tree is empty, so there is nothing to count.

Constraints

  • The number of nodes in the tree is between 0 and 10^5.
  • Each node value is between -10^4 and 10^4.
  • Each node has at most one left child and one right child.
  • The input is a valid binary tree in level-order form with no cycles.

Constraints that matter

  • Up to 10^5 nodes means a solution that re-walks a root-to-node path for every node can cost about 10^10 steps in a skewed tree. You need roughly linear time.
  • A tree with 10^5 nodes can be a single chain of depth 10^5. Recursive code in Python overflows the default call stack, so an explicit stack is the safe choice.
  • Values can be negative and can repeat. Starting a running maximum at 0 is wrong, and the comparison must use >= so ties count as good.
  • The tree may be empty. Handle a null root before touching any field.
  • Values fit easily in 32-bit integers, so there is no overflow concern when you compare and take maxima.

View on LeetCode

Hints

Hint 1

The definition of a good node depends only on the path from the root to that node.

Hint 2

Treat every node as its own question.

Solution

Intuition

The definition of a good node depends only on the path from the root to that node. That path is the same prefix that the node's parent already walked. So you never need to look back up the tree. You need only one number per path: the largest value seen so far.

Picture walking down a branching trail with one notepad that records the tallest hill you have passed so far. At each fork you copy the notepad for each path, so a tall hill on one trail never changes the notes on another, and you count a spot when it is at least as tall as the note.

This is a preorder traversal with state passed downward. You visit a node, decide something about it using what its ancestors told you, then hand an updated summary to each child. The summary here is the path maximum. The left and right children each get their own copy, so a big value in the left subtree never affects the right subtree.

A node is good exactly when its value is at least the maximum of its ancestors. The path maximum for a child is the larger of the parent's path maximum and the parent's value. That update takes constant time, so every node costs O(1) and the whole tree costs O(n).

You can spot this pattern whenever a question asks about a node relative to its ancestors: is it larger than all of them, does it match a running sum, does it extend a path. If the answer for a node depends on the root-to-node path, carry a summary of that path down the recursion.

Watch the pattern animation

Worked example

Input: root = [5,8,3,7,null,null,4]
Output: 2
Explanation:
The tree has root 5 with children 8 and 3. Node 8 has left child 7, and node 3 has right child 4. The root 5 is good. Node 8 is good because 8 >= 5.

Node 3 fails because 5 is above it. Node 7 fails because 8 is above it. Node 4 fails because 5 is above it. That leaves 2 good nodes.

Approach 1: Brute force: walk up from every node

Treat every node as its own question. For each node, look at every ancestor above it and check whether any ancestor has a larger value. If none does, the node is good.

To walk upward you need parent links. Tree nodes do not store them, so first list all nodes in level order and record each node's parent index in a parallel array. Then loop over every node and follow parent indexes until you reach the root or find a larger ancestor.

Steps

  1. Return 0 if the root is null.
  2. Build a list nodes in level order and a list parent where parent[i] is the index of node i's parent, with -1 for the root.
  3. Set count to 0.
  4. For each index i, set j = parent[i] and mark the node good.
  5. While j is not -1, check whether nodes[j].val > nodes[i].val. If so, mark the node not good and stop.
  6. Otherwise move up with j = parent[j].
  7. Add 1 to count when the node is still good after the walk.
  8. Return count.

Dry run

Level order gives indexes 0 to 4: node 5 (parent -1), node 8 (parent 0), node 3 (parent 0), node 7 (parent 1), node 4 (parent 2).

  • Index 0, value 5: no ancestors, so it is good. count = 1.
  • Index 1, value 8: ancestor 5 is not larger than 8, so it is good. count = 2.
  • Index 2, value 3: ancestor 5 is larger than 3, so it is not good.
  • Index 3, value 7: parent 8 is larger than 7, so it is not good.
  • Index 4, value 4: parent 3 is fine, then ancestor 5 is larger than 4, so it is not good.

The result is 2, which matches the expected output.

Complexity

TimeO(n * h), which is O(n^2) in the worst case
SpaceO(n)

Here n is the number of nodes and h is the tree height. Each node walks up at most h ancestors, so the total work is at most n * h. In a skewed chain h equals n, which gives O(n^2), about 10^10 steps at n = 10^5. The nodes and parent lists each hold n entries, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def goodNodes(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        nodes = [root]
        parent = [-1]
        i = 0
        while i < len(nodes):
            node = nodes[i]
            if node.left is not None:
                nodes.append(node.left)
                parent.append(i)
            if node.right is not None:
                nodes.append(node.right)
                parent.append(i)
            i += 1

        count = 0
        for i in range(len(nodes)):
            good = True
            j = parent[i]
            while j != -1:
                if nodes[j].val > nodes[i].val:
                    good = False
                    break
                j = parent[j]
            if good:
                count += 1
        return count
Recursive Preorder Traversal pattern infographic for Count Good Nodes in Binary Tree

Solution pattern

Recursive Preorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Preorder DFS carrying the path maximumOptimalRecursive Preorder Traversal

What's slow: the brute force re-walks the same ancestors for every node. A node at depth 50,000 repeats almost all the work its parent did, because their paths differ by one step.

The insight that fixes it: push the answer for the path down with you. Each node needs only one number from its ancestors, the largest value on the path so far. Compare the node to that number, then give each child the larger of that number and the node's own value.

Use an explicit stack of (node, maxSoFar) pairs instead of recursion. A chain of 10^5 nodes would overflow Python's call stack, and the explicit stack runs the same preorder logic without that risk. Pushing the right child first makes the left child pop first, which keeps preorder order, though the count does not depend on order.

Steps

  1. Return 0 if the root is null.
  2. Set count to 0 and push (root, root.val) on the stack.
  3. While the stack is not empty, pop a pair (node, mx).
  4. If node.val >= mx, increase count. The node ties or beats every ancestor.
  5. Compute next = max(mx, node.val).
  6. Push the right child with next if it exists.
  7. Push the left child with next if it exists.
  8. Return count when the stack is empty.

Dry run

Each stack entry is (value, maxSoFar). The tree is 5 with children 8 and 3, 8 has left child 7, and 3 has right child 4.

StepPopGood? (val >= max)countnext maxStack after pushes (top on right)
startnonenone0none(5,5)
1(5,5)5 >= 5 yes15(3,5) (8,5)
2(8,5)8 >= 5 yes28(3,5) (7,8)
3(7,8)7 >= 8 no28(3,5)
4(3,5)3 >= 5 no25(4,5)
5(4,5)4 >= 5 no25empty

The stack is empty, and count is 2, which matches the expected output. Node 7 was compared with 8, not 5, because its branch passed through the larger node 8. Node 4 was compared with 5, because the 8 branch never reached the right subtree.

Complexity

TimeO(n)
SpaceO(h), which is O(n) in the worst case

Here n is the number of nodes and h is the tree height. Every node is pushed once and popped once, and each pop does a comparison, a max, and at most two pushes, all O(1). That gives O(n) time. The stack holds the unvisited right siblings along one root-to-leaf path plus the current branch, so it is at most about h entries deep in a balanced tree and up to n in a chain-shaped tree.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def goodNodes(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        count = 0
        stack = [(root, root.val)]  # (node, max value on path above and including parent)
        while stack:
            node, mx = stack.pop()
            if node.val >= mx:
                count += 1
            nxt = max(mx, node.val)
            if node.right is not None:
                stack.append((node.right, nxt))
            if node.left is not None:
                stack.append((node.left, nxt))
        return count

Common mistakes

  • Using node.val > mx instead of node.val >= mx. A node equal to the path maximum is good, so ties must count. The fix is to compare with >=.
  • Starting the running maximum at 0 with stack = [(root, 0)]. Values can be negative, so a root of -5 would be judged against 0 and wrongly rejected. Start with root.val or negative infinity.
  • Passing the parent's old maximum to the children instead of max(mx, node.val). Then a child under a new larger node is compared with a stale value and can be counted wrongly. Compute next before pushing the children.
  • Using one global max variable that you update during the traversal. A big value in the left subtree then leaks into the right subtree. Give each branch its own copy by passing the maximum as a parameter or stack entry.
  • Forgetting the null root check. root.val on an empty tree crashes, and the expected answer is 0. Return early before reading any field.
  • Writing the recursive version in Python for a chain of 10^5 nodes. It hits the recursion limit and raises an error. Use the explicit stack, or raise the limit and accept the risk.

Edge cases

  • Empty tree []: return 0 without reading any field.
  • Single node [-7]: the root is always good, so return 1, even for a negative value.
  • Strictly decreasing chain [5,4,3,2,1] as a left-leaning tree: only the root is good, so return 1.
  • Strictly increasing chain such as [1,2,3,4] as a right-leaning tree: every node is good, so return 4.
  • All equal values [3,3,3,3]: ties count, so every node is good and the answer equals the node count.
  • Chain of 10^5 nodes: the explicit stack handles it, while naive recursion in Python can overflow.

Follow-ups interviewers ask

How would you write this recursively, and what is its space cost?
Define dfs(node, mx): if node is null return 0, add 1 if node.val >= mx, then recurse into both children with max(mx, node.val) and add the results. Time is O(n). Space is O(h) for the call stack, so O(log n) for a balanced tree and O(n) for a chain, which is why Python needs the explicit stack for deep input.
Can a BFS solve it too?
Yes. Store (node, maxSoFar) in a queue instead of a stack. Each node still gets the maximum of its own root-to-node path, so the count is the same. The visit order differs from preorder, but the logic and the O(n) time do not change. A queue can hold a whole level, so space is O(width), which can be O(n).
What if you must return the list of good nodes, or count nodes that are strictly greater than all ancestors?
To return the nodes, append each good node to a result list when the check passes. That adds O(k) space for k good nodes. For the strict version, change >= to > and start the root with negative infinity so the root still counts. Everything else stays identical.

Count Good Nodes in Binary Tree FAQ

What is the time complexity of Count Good Nodes in Binary Tree?

The optimal solution is O(n), where n is the number of nodes. Each node is visited once and does constant work: one comparison, one max, and at most two pushes. The brute force that walks up from every node is O(n * h), which is O(n^2) on a skewed tree.

Why use preorder DFS for Count Good Nodes in Binary Tree?

A node's status depends only on its ancestors, and preorder visits a node before its children. That lets you pass a path summary, the maximum so far, from parent to child. No node ever has to look back up the tree, so the work per node is constant.

Can Count Good Nodes in Binary Tree be solved in O(1) extra space?

Not with the standard methods. You need the path maximum for each branch, and the traversal needs either a call stack or an explicit stack of height h. A Morris-style traversal can avoid the stack, but it does not track per-branch maximums easily, so in practice the space is O(h).

Does the root always count as a good node?

Yes, when the tree is not empty. The path from the root to itself contains only the root, so nothing on it is larger. Initialize the path maximum with the root's value so the check passes.

Why is >= used and not > in LeetCode 1448?

The definition says no node on the path may be greater than the current node. Equal values do not violate that. So a node equal to the path maximum is good, and the check must be node.val >= maxSoFar.

Why does the Python solution use an explicit stack?

The tree can have 10^5 nodes in a single chain. Python's default recursion limit is about 1000 frames, so a recursive solution can raise a recursion error on deep inputs. An explicit stack stores the same (node, maximum) pairs on the heap and runs the same preorder logic safely.

Asked at

See which companies ask this — Pro

Practise it