Count Good Nodes in Binary Tree LeetCode solution in Python
1class Solution:2def goodNodes(self, root: TreeNode) -> int:3# Our counter for the good nodes.4count = 056def helper(node, m):7nonlocal count8# If we run out of nodes return.9if not node:10return11# If the current node val is >= the largest observed in the path thus far.12if node.val >= m:13# Add 1 to the count and update the max observed value.14count += 115m = max(m, node.val)16# Traverse l and r subtrees.17helper(node.left, m)18helper(node.right, m)1920helper(root, root.val)21return count