LeetCode之Sum of Nodes with Even-Valued Grandparent(Kotlin)

问题:



方法:
通过深度优先遍历,向下传递父节点和祖节点,然后判断祖节点是否为偶数,当祖节点为偶数时进行加和,遍历完成后输出结果。

class SumOfNodesWithEvenValuedGrandparent {
    private var sum: Int = 0

    fun sumEvenGrandparent(root: TreeNode?): Int {
        sum = 0
        dfs(root, null, null)
        return sum
    }

    private fun dfs(root: TreeNode?, grandparent: TreeNode?, parent: TreeNode?) {
        if (root == null) {
            return
        }
        if (grandparent?.`val`?.rem(2) == 0) {
            sum += root.`val`
        }
        dfs(root.left, parent, root)
        dfs(root.right, parent, root)
    }
}

fun main() {

}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Sum of Nodes with Even-Valued Grandparent(Kotlin))