问题:
方法:
通过深度优先遍历,向下传递父节点和祖节点,然后判断祖节点是否为偶数,当祖节点为偶数时进行加和,遍历完成后输出结果。
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() {
}
有问题随时沟通
网友评论