leetcode之104二叉树的最大深度Golang

本题采用深度优先遍历

二叉树结构如下:

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

我们的思路是对于求整棵树的深度,就是根节点的左子树的深度或者根结点的右子树的深度加1,那么,使用递归的方式就是

depth(root)=1+max(depth(root.Left),depth(root.Right))

代码如下:

func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    leftDepth := maxDepth(root.Left)
    rightDepth := maxDepth(root.Right)
    if leftDepth >= rightDepth {
        return 1 + leftDepth
    }
    return 1 + rightDepth
}
 

  

posted @ 2020-09-26 19:31  胖胖咩  阅读(258)  评论(0)    收藏  举报