LeetCode之Deepest Leaves Sum(Kotlin)

问题:



方法:
题目比较简单,参考代码即可,主要就是需要刷新最大深度,当出现更大深度时丢弃之前的sum,重新开始求和。

class DeepestLeavesSum {
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    var sum = 0
    var maxDepth = 0

    fun deepestLeavesSum(root: TreeNode?): Int {
        sum = 0
        root?.let { dfs(it, 0) }
        return sum
    }

    private fun dfs(root: TreeNode, depth: Int) {
        root.left?.let { dfs(it, depth + 1) }
        root.right?.let { dfs(it, depth + 1) }
        if (root.left == null && root.right == null) {
            if (maxDepth == depth) {
                sum+=root.`val`
            } else if (maxDepth < depth) {
                sum = root.`val`
                maxDepth = depth
            }
        }
    }
}

fun main() {

}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Deepest Leaves Sum(Kotlin))