15% off all plans & roadmaps Use code
See plansCount Good Nodes in Binary Tree
- LeetCode 1448
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Recursive Preorder Traversal
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.
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.
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
- Return 0 if the root is null.
- Build a list
nodesin level order and a listparentwhereparent[i]is the index of node i's parent, with -1 for the root. - Set
countto 0. - For each index i, set
j = parent[i]and mark the node good. - While
jis not -1, check whethernodes[j].val > nodes[i].val. If so, mark the node not good and stop. - Otherwise move up with
j = parent[j]. - Add 1 to
countwhen the node is still good after the walk. - 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
| Time | O(n * h), which is O(n^2) in the worst case |
|---|---|
| Space | O(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 countJavaTested in our runner
import java.util.*;
class Solution {
public int goodNodes(TreeNode root) {
if (root == null) {
return 0;
}
List<TreeNode> nodes = new ArrayList<>();
List<Integer> parent = new ArrayList<>();
nodes.add(root);
parent.add(-1);
for (int i = 0; i < nodes.size(); i++) {
TreeNode node = nodes.get(i);
if (node.left != null) {
nodes.add(node.left);
parent.add(i);
}
if (node.right != null) {
nodes.add(node.right);
parent.add(i);
}
}
int count = 0;
for (int i = 0; i < nodes.size(); i++) {
boolean good = true;
int j = parent.get(i);
while (j != -1) {
if (nodes.get(j).val > nodes.get(i).val) {
good = false;
break;
}
j = parent.get(j);
}
if (good) {
count++;
}
}
return count;
}
}C++Tested in our runner
class Solution {
public:
int goodNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
std::vector<TreeNode*> nodes;
std::vector<int> parent;
nodes.push_back(root);
parent.push_back(-1);
for (int i = 0; i < (int)nodes.size(); i++) {
TreeNode* node = nodes[i];
if (node->left != nullptr) {
nodes.push_back(node->left);
parent.push_back(i);
}
if (node->right != nullptr) {
nodes.push_back(node->right);
parent.push_back(i);
}
}
int count = 0;
for (int i = 0; i < (int)nodes.size(); i++) {
bool good = true;
int j = parent[i];
while (j != -1) {
if (nodes[j]->val > nodes[i]->val) {
good = false;
break;
}
j = parent[j];
}
if (good) {
count++;
}
}
return count;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root) {
if (root === null) {
return 0;
}
const nodes = [root];
const parent = [-1];
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node.left !== null) {
nodes.push(node.left);
parent.push(i);
}
if (node.right !== null) {
nodes.push(node.right);
parent.push(i);
}
}
let count = 0;
for (let i = 0; i < nodes.length; i++) {
let good = true;
let j = parent[i];
while (j !== -1) {
if (nodes[j].val > nodes[i].val) {
good = false;
break;
}
j = parent[j];
}
if (good) {
count++;
}
}
return count;
};GoTested in our runner
func goodNodes(root *TreeNode) int {
if root == nil {
return 0
}
nodes := []*TreeNode{root}
parent := []int{-1}
for i := 0; i < len(nodes); i++ {
node := nodes[i]
if node.Left != nil {
nodes = append(nodes, node.Left)
parent = append(parent, i)
}
if node.Right != nil {
nodes = append(nodes, node.Right)
parent = append(parent, i)
}
}
count := 0
for i := 0; i < len(nodes); i++ {
good := true
j := parent[i]
for j != -1 {
if nodes[j].Val > nodes[i].Val {
good = false
break
}
j = parent[j]
}
if good {
count++
}
}
return count
}C#Tested in our runner
public class Solution {
public int goodNodes(TreeNode root) {
if (root == null) {
return 0;
}
var nodes = new List<TreeNode> { root };
var parent = new List<int> { -1 };
for (int i = 0; i < nodes.Count; i++) {
TreeNode node = nodes[i];
if (node.left != null) {
nodes.Add(node.left);
parent.Add(i);
}
if (node.right != null) {
nodes.Add(node.right);
parent.Add(i);
}
}
int count = 0;
for (int i = 0; i < nodes.Count; i++) {
bool good = true;
int j = parent[i];
while (j != -1) {
if (nodes[j].val > nodes[i].val) {
good = false;
break;
}
j = parent[j];
}
if (good) {
count++;
}
}
return count;
}
}
Solution pattern
Recursive Preorder Traversal
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
- Return 0 if the root is null.
- Set
countto 0 and push(root, root.val)on the stack. - While the stack is not empty, pop a pair
(node, mx). - If
node.val >= mx, increasecount. The node ties or beats every ancestor. - Compute
next = max(mx, node.val). - Push the right child with
nextif it exists. - Push the left child with
nextif it exists. - Return
countwhen 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.
| Step | Pop | Good? (val >= max) | count | next max | Stack after pushes (top on right) |
|---|---|---|---|---|---|
| start | none | none | 0 | none | (5,5) |
| 1 | (5,5) | 5 >= 5 yes | 1 | 5 | (3,5) (8,5) |
| 2 | (8,5) | 8 >= 5 yes | 2 | 8 | (3,5) (7,8) |
| 3 | (7,8) | 7 >= 8 no | 2 | 8 | (3,5) |
| 4 | (3,5) | 3 >= 5 no | 2 | 5 | (4,5) |
| 5 | (4,5) | 4 >= 5 no | 2 | 5 | empty |
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
| Time | O(n) |
|---|---|
| Space | O(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 countJavaTested in our runner
import java.util.*;
class Solution {
public int goodNodes(TreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
Deque<TreeNode> nodeStack = new ArrayDeque<>();
Deque<Integer> maxStack = new ArrayDeque<>();
nodeStack.push(root);
maxStack.push(root.val);
while (!nodeStack.isEmpty()) {
TreeNode node = nodeStack.pop();
int mx = maxStack.pop();
if (node.val >= mx) {
count++;
}
int next = Math.max(mx, node.val);
if (node.right != null) {
nodeStack.push(node.right);
maxStack.push(next);
}
if (node.left != null) {
nodeStack.push(node.left);
maxStack.push(next);
}
}
return count;
}
}C++Tested in our runner
class Solution {
public:
int goodNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int count = 0;
std::vector<std::pair<TreeNode*, int>> stack;
stack.push_back({root, root->val});
while (!stack.empty()) {
TreeNode* node = stack.back().first;
int mx = stack.back().second;
stack.pop_back();
if (node->val >= mx) {
count++;
}
int next = std::max(mx, node->val);
if (node->right != nullptr) {
stack.push_back({node->right, next});
}
if (node->left != nullptr) {
stack.push_back({node->left, next});
}
}
return count;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root) {
if (root === null) {
return 0;
}
let count = 0;
const stack = [[root, root.val]];
while (stack.length > 0) {
const [node, mx] = stack.pop();
if (node.val >= mx) {
count++;
}
const next = Math.max(mx, node.val);
if (node.right !== null) {
stack.push([node.right, next]);
}
if (node.left !== null) {
stack.push([node.left, next]);
}
}
return count;
};GoTested in our runner
func goodNodes(root *TreeNode) int {
if root == nil {
return 0
}
type frame struct {
node *TreeNode
mx int
}
count := 0
stack := []frame{{root, root.Val}}
for len(stack) > 0 {
f := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if f.node.Val >= f.mx {
count++
}
next := f.mx
if f.node.Val > next {
next = f.node.Val
}
if f.node.Right != nil {
stack = append(stack, frame{f.node.Right, next})
}
if f.node.Left != nil {
stack = append(stack, frame{f.node.Left, next})
}
}
return count
}C#Tested in our runner
public class Solution {
public int goodNodes(TreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
var stack = new Stack<(TreeNode node, int mx)>();
stack.Push((root, root.val));
while (stack.Count > 0) {
var (node, mx) = stack.Pop();
if (node.val >= mx) {
count++;
}
int next = Math.Max(mx, node.val);
if (node.right != null) {
stack.Push((node.right, next));
}
if (node.left != null) {
stack.Push((node.left, next));
}
}
return count;
}
}Common mistakes
- Using
node.val > mxinstead ofnode.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 withroot.valor 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. Computenextbefore pushing the children. - Using one global
maxvariable 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.valon 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 ifnode.val >= mx, then recurse into both children withmax(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
Related problems
- Construct Binary Tree from Preorder and Inorder Traversal · same technique: Recursive Preorder Traversal
- Insert into a Binary Search Tree · same technique: Recursive Preorder Traversal
- Construct Quad Tree · same technique: Recursive Preorder Traversal
- Flatten Binary Tree to Linked List · same technique: Recursive Preorder Traversal
- Smallest String Starting From Leaf · same technique: Recursive Preorder Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Level Order Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Right Side View · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)