/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcminDepth(root *TreeNode)int {
if root == nil { return0 }
if root.Left == nil { return minDepth(root.Right) + 1 }
if root.Right == nil { return minDepth(root.Left) + 1 }
//之所以定义left和right,为了防止下面return时还有再次计算 left := minDepth(root.Left) right := minDepth(root.Right) if left > right { return right + 1 } else { return left + 1 }