[LeetCode] 1448. Count Good Nodes in Binary Tree(Kotlin)

0

LeetCode

목록 보기
49/58
post-thumbnail

[LeetCode] 1448. Count Good Nodes in Binary Tree(Kotlin)

input: [2,null,4,10,8,null,null,4]
answer: 4

풀이

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */

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
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글