美文网首页
LeetCode之Sum of Nodes with Even-

LeetCode之Sum of Nodes with Even-

作者: 糕冷羊 | 来源:发表于2020-10-29 21:46 被阅读0次

    问题:



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

    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-

          本文链接:https://www.haomeiwen.com/subject/roilvktx.html