[leetcode] 1448. Count Good Nodes in Binary Tree

kldaji·2022년 9월 1일
0

leetcode

목록 보기
44/56

class Solution {
    fun goodNodes(root: TreeNode?): Int {
        var good = 0
        
        good += dfs(root, root!!.`val`) // number of nodes >= 1
        
        return good
    }
    
    fun dfs(root: TreeNode?, maxValueInPath: Int): Int {
        root ?: return 0
        
        var temp = 0
        var newMaxVal = maxValueInPath
        
        if (root.`val` >= maxValueInPath) {
            temp++
            newMaxVal = root.`val`
        }
        
        temp += dfs(root.left, newMaxVal)
        temp += dfs(root.right, newMaxVal)
        
        return temp
    }
}
profile
다양한 관점에서 다양한 방법으로 문제 해결을 지향하는 안드로이드 개발자 입니다.

0개의 댓글