美文网首页
LeetCode之Diameter of Binary Tree

LeetCode之Diameter of Binary Tree

作者: 糕冷羊 | 来源:发表于2021-10-11 16:25 被阅读0次

问题:



方法:
DFS问题的变种,在遍历过程中在每个节点获取左子树与右子树的最大深度,然后计算左右深度和,取所有节点中最大的和即为结果。

package com.eric.leetcode

class DiameterOfBinaryTree {
    var result = 0;
    fun diameterOfBinaryTree(root: TreeNode?): Int {
        diameter(root)
        return result
    }

    private fun diameter(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }

        val left = diameter(root.left)
        val right = diameter(root.right)

        result = maxOf(1 + left + right, result)
        return 1 + maxOf(left, right)
    }
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Diameter of Binary Tree

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