题目:给定一个二叉树,找出其最大深度。 语言:Golang
解法①:
// 16ms, beat 12.46%
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := maxDepth(root.Left)
rightDepth := maxDepth(root.Right)
if leftDepth > rightDepth {
return leftDepth + 1
} else {
return rightDepth + 1
}
}
解法②:
// 8ms, beat 100%
func maxDepth(root *TreeNode) int {
if root != nil {
leftDepth := maxDepth(root.Left)
rightDepth := maxDepth(root.Right)
if leftDepth > rightDepth {
return 1+leftDepth
}
return 1+rightDepth
}
return 0
}
实际提交到 leetcode 上,前者耗时 16ms,后者耗时 8ms。
初学 Golang,请问这两段代码为什么执行时间会差两倍?