[Swift]LeetCode111. 二叉树的最小深度 | Minimum Depth of Binary Tree
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9708887.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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.
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最小深度 2.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func minDepth(_ root: TreeNode?) -> Int { 16 //深度优先搜索DFS 17 if root == nil {return 0} 18 if root!.left == nil && root!.right == nil 19 { 20 return 1 21 } 22 if root!.left == nil 23 { 24 return minDepth(root!.right) + 1 25 } 26 else if root!.right == nil 27 { 28 return minDepth(root!.left) + 1 29 } 30 else 31 { 32 let depthLeft:Int = minDepth(root!.left) 33 let depthRight:Int = minDepth(root!.right) 34 return (1 + ((depthLeft < depthRight) ? depthLeft : depthRight)) 35 } 36 } 37 }
32ms
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func minDepth(_ root: TreeNode?) -> Int { 16 guard let root = root else { return 0 } 17 let left = minDepth(root.left) 18 let right = minDepth(root.right) 19 return 1 + ((left == 0 || right == 0) ? max(left, right) : min(left, right)) 20 } 21 }
28ms
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func minDepth(_ root: TreeNode?) -> Int { 16 guard let root = root else { 17 return 0 18 } 19 20 let left = minDepth(root.left) 21 let right = minDepth(root.right) 22 23 if left == 0 { 24 return right + 1 25 } else if right == 0 { 26 return left + 1 27 } else { 28 return min(left, right) + 1 29 } 30 } 31 }