Solution 1

  • TimeO(n)
  • SpaceO(h)

where, n is the total number of nodes, and h is the height of the tree (can be n if it's a skewed tree in worst cases)
Solved in 6 mins, all by yourself! Good job! Incredible actually!

Python
# 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:
    '''
    Time complexity: O(n)
    Space complexity: O(h)
    where, n is the total number of nodes, and h is the height of the tree (can be n if it's a skewed tree in worst cases)
    Solved in 6 mins, all by yourself! Good job! Incredible actually!
    '''
    def goodNodes(self, root: TreeNode) -> int:

        def dfs(node, pathMax):
            if not node:
                return 0
            val = 0
            if node.val >= pathMax:
                pathMax = node.val
                val += 1
            return val + dfs(node.left, pathMax) + dfs(node.right, pathMax)
        
        return dfs(root, root.val)
Leet Code/python.py · L1781–1806