Count Good Nodes in Binary Tree Problem
Description
LeetCode Problem 1448.
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
- The number of nodes in the binary tree is in the range
[1, 10^5]. - Each node's value is between
[-10^4, 10^4].
Solution
Approach: DFS with the Path Maximum
A node is good when no node above it on the path from the root has a larger value. In other words, it is good when its value is at least the maximum of all values above it.
So during a DFS we carry best, the largest value seen on the path from the root to the current node's parent. At each node:
- it is good if
node.val >= best; - then the children see
max(best, node.val)as their path maximum.
The count for a subtree is the node's own 0 or 1 plus the counts of its two subtrees. Start with best lower than any value, so the root is always good.
Note the comparison is >=, not >: a node equal to the maximum above it is still good (in Example 2 the second 3 is good).
Complexity: O(n) time and O(h) extra space for the recursion, where h is the height of the tree.
class Solution:
def goodNodes(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], best: int) -> int:
# best: the largest value on the path from the root down to node's parent.
if node is None:
return 0
good = 1 if node.val >= best else 0
best = max(best, node.val)
return good + dfs(node.left, best) + dfs(node.right, best)
return dfs(root, -10**9)