时间复杂度:O(n)
解题思路
DFS的思想。只要有孩子就遍历。
从叶子结点向根节点统计高度,空结点是0。
AC代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
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
}
感悟
自己写的是函数值写法,代码有点长。看了官方题解发现真的是短小精悍。