Problem : https://leetcode.com/problems/count-good-nodes-in-binary-tree/
Use DFS to find number of nodes where value not less than the current local maximum value.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
result = 0
stack = [(root, -10**4)]
while stack:
node, mx = stack.pop()
if mx <= node.val:
result += 1
mx = node.val
if node.right:
stack.append((node.right, mx))
if node.left:
stack.append((node.left, mx))
return result
No comments:
Post a Comment