[LeetCode] 1448. Count Good Nodes in Binary Tree(Kotlin)
input: [2,null,4,10,8,null,null,4]
answer: 4
풀이
import kotlin.math.*
class Solution {
fun goodNodes(root: TreeNode?): Int {
if(root == null) return 0
return goodNodes(root, root.`val`)
}
private fun goodNodes(root: TreeNode, maxValOfPath: Int): Int{
var result = 0
if(root.`val` >= maxValOfPath) result++
root.left?.let{
result += goodNodes(it, max(maxValOfPath, root.`val`))
}
root.right?.let{
result += goodNodes(it, max(maxValOfPath, root.`val`))
}
return result
}
}