We just trace the current maximum value from the root to the current node.
fun goodNodes(root: TreeNode?): Int {
return dfs(root, root.`val`)
}
private fun dfs(root: TreeNode?, max: Int): Int {
if (root == null) return 0
var count = if (root.`val` >= max) 1 else 0
val nextMax = maxOf(max, root.`val`)
count += dfs(root.left, nextMax)
count += dfs(root.right, nextMax)
return count
}- Time Complexity:
O(n)wherenis the number of nodes in the tree. - Space Complexity:
O(h)wherehis the height of the tree.