SDE & MLE Prep

1448. Count Good Nodes in Binary Tree

Problem

A node is "good" if no node on the path from the root to it has a greater value. Count the good nodes of a binary tree.

Example: [3,1,4,3,null,1,5] → 4

Constraints: up to 10⁵ nodes.

Pass down the max value on the path from the root; a node is good if node.val ≥ pathMax.

Complexity: O(n).

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(node, mx):
            if not node:
                return 0
            good = node.val >= mx
            mx = max(mx, node.val)
            return good + dfs(node.left, mx) + dfs(node.right, mx)

        return dfs(root, root.val)