二叉树的最小深度

题目

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

  3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

 

题解

最直接的思路就是递归。

我们用深度优先搜索来解决这个问题。

func minDepth(_ root: TreeNode?) -> Int {
    guard let tree = root else { return 0 }
    if tree.left == nil, tree.right == nil {
        return 1
    }
    var minDeepCount = Int.max
    if let left = tree.left {
        minDeepCount = min(minDepth(left), minDeepCount)
    }
    if let right = tree.right {
        minDeepCount = min(minDepth(right), minDeepCount)
    }
    return minDeepCount + 1
}
posted @ 2020-01-18 19:32  国孩  阅读(191)  评论(0编辑  收藏  举报