A node X in a binary tree is good if no node on the path from the root to X has a value greater than X. Return the number of good nodes.
Same rule, iteratively: the queue holds each node together with the max on the path to it.
1function goodNodes(root: TreeNode | null): number {2if (!root) return 0;3const queue: [TreeNode, number][] = [[root, -Infinity]];4let good = 0;5while (queue.length) {6const [n, max] = queue.shift()!;7if (n.val >= max) good++;8const m = Math.max(max, n.val);9if (n.left) queue.push([n.left, m]);10if (n.right) queue.push([n.right, m]);11}12return good;13}
Queue the root with max = −∞.
Space: play/pause · ←/→: step