Count Good Nodes in Binary Tree LeetCode solution in Python

1
class Solution:
2
def goodNodes(self, root: TreeNode) -> int:
3
# Our counter for the good nodes.
4
count = 0
5

6
def helper(node, m):
7
nonlocal count
8
# If we run out of nodes return.
9
if not node:
10
return
11
# If the current node val is >= the largest observed in the path thus far.
12
if node.val >= m:
13
# Add 1 to the count and update the max observed value.
14
count += 1
15
m = max(m, node.val)
16
# Traverse l and r subtrees.
17
helper(node.left, m)
18
helper(node.right, m)
19

20
helper(root, root.val)
21
return count

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0