首页 > 其他 > 详细

二叉树的最小深度

时间:2020-01-18 19:59:23      阅读:77      评论:0      收藏:0      [点我收藏+]

题目

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

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

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

示例:

给定二叉树 [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
}

二叉树的最小深度

原文:https://www.cnblogs.com/guohai-stronger/p/12209476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!