The problem asks to count the number of "good" nodes in a binary tree, where a node is good if its value is greater than or equal to the maximum value on the path from the root to that node.
The solution uses an iterative depth-first search (DFS) with a stack to traverse the tree and track the maximum value along each path. Here’s how it works:
good_nodes to 0 and a stack with the root node and an initial maximum value of negative infinity (to ensure the root is always good).largest):
largest, increment good_nodes, as the node is good.largest to the maximum of the current largest and the node’s value, as this is the new maximum for the path to the node’s children.largest.good_nodes, the total count of good nodes.n is the number of nodes. The stack stores at most O(h) nodes, where h is the tree’s height, which is O(n) in the worst case (e.g., a skewed tree), so the space complexity is O(n).class Solution:
def goodNodes(self, root: TreeNode) -> int:
good_nodes = 0
stk = [(root, float("-inf"))]
while stk:
node, largest = stk.pop()
if largest <= node.val:
good_nodes += 1
largest = max(largest, node.val)
if node.right: stk.append((node.right, largest))
if node.left: stk.append((node.left, largest))
return good_nodes
# Time Complexity: O(n)
# Space Complexity: O(n)