题目描述
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
解题思路
我们可以判断当一个节点只有一个子树时, 我们可以我们可以得到当前节点的深度是这个子树的高度+1, 我们最终获取根节点的左右子树的高度, 返回小的值就可以了
示例代码
func minDepth(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
if root?.left == nil && root?.right != nil {
return minDepth(root?.right) + 1
}
if root?.right == nil && root?.left != nil {
return minDepth(root?.left) + 1
}
let lf = minDepth(root?.left) + 1
let rt = minDepth(root?.right) + 1
return lf > rt ? rt : lf
}