Count Good Nodes in Binary Tree (Leetcode 1448)

Problem Link: https://leetcode.com/problems/count-good-nodes-in-binary-tree/

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
            
        def fun(root,maxx):
            ans=0
            if(root is None):
                return 0
            if(root.val>=maxx):
                ans+=1
                maxx=root.val
            l=fun(root.left,maxx)
            r=fun(root.right,maxx)
            ans=ans+l+r
            return ans
        
        return fun(root,float('-inf'))

Last updated