美文网首页
104. Maximum Depth of Bianry Tre

104. Maximum Depth of Bianry Tre

作者: sarto | 来源:发表于2022-05-23 20:48 被阅读0次

题目

求二叉树的最大深度

解析

二叉树的最大深度,是左子树深度加 1 和右子树深度加 1 的最大值。即 f(node) = max(f(node.left), f(node.right)) +1

伪代码

return max(f(node.left), f(node.right)) + 1

代码

func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
image.png

相关文章

网友评论

      本文标题:104. Maximum Depth of Bianry Tre

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