Count Good Nodes in Binary Tree
Problem Statement
You are given the root of a binary tree.
A node X is good if no node on the path from the root down to X has a value greater than X's value. The root is always good. Return how many good nodes the tree has.
The root of a binary tree. It has at least one node.
The number of good nodes.
The good nodes are the root 3, the 3 under 1 (path 3, 1, 3), 4 (path 3, 4) and 5 (path 3, 4, 5). The 1 under 4 is not good, because 4 is bigger.
Node 2 has the path 3, 3, 2. The 3 above it is bigger than 2, so 2 is not good. The other three nodes are good.
The only node is the root, which is always good.
- • The tree has between 1 and 10^5 nodes.
- • −10^4 ≤ Node.val ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For every node, read the path from the root again and find its biggest value
Pass down the biggest value above each node; a node is good when it is at least that
Keep the path from the root in a stack. For each node, walk the whole stack again to find the biggest value on its path, including the node itself. If the node's value equals or beats that biggest value, it is good.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.