mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 111.二叉树的最小深度 Swift版本
This commit is contained in:
@ -404,8 +404,51 @@ var minDepth = function(root) {
|
||||
};
|
||||
```
|
||||
|
||||
## Swift
|
||||
|
||||
> 递归
|
||||
```Swift
|
||||
func minDepth(_ root: TreeNode?) -> Int {
|
||||
guard let root = root else {
|
||||
return 0
|
||||
}
|
||||
if root.left == nil && root.right != nil {
|
||||
return 1 + minDepth(root.right)
|
||||
}
|
||||
if root.left != nil && root.right == nil {
|
||||
return 1 + minDepth(root.left)
|
||||
}
|
||||
return 1 + min(minDepth(root.left), minDepth(root.right))
|
||||
}
|
||||
```
|
||||
|
||||
> 迭代
|
||||
```Swift
|
||||
func minDepth(_ root: TreeNode?) -> Int {
|
||||
guard let root = root else {
|
||||
return 0
|
||||
}
|
||||
var res = 0
|
||||
var queue = [TreeNode]()
|
||||
queue.append(root)
|
||||
while !queue.isEmpty {
|
||||
res += 1
|
||||
for _ in 0 ..< queue.count {
|
||||
let node = queue.removeFirst()
|
||||
if node.left == nil && node.right == nil {
|
||||
return res
|
||||
}
|
||||
if let left = node.left {
|
||||
queue.append(left)
|
||||
}
|
||||
if let right = node.right {
|
||||
queue.append(right)
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user