mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 104.二叉树的最大深度 Swift版本
This commit is contained in:
@ -653,5 +653,82 @@ int maxDepth(struct TreeNode* root){
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Swift
|
||||||
|
|
||||||
|
>二叉树最大深度
|
||||||
|
```swift
|
||||||
|
// 递归 - 后序
|
||||||
|
func maxDepth1(_ root: TreeNode?) -> Int {
|
||||||
|
return _maxDepth1(root)
|
||||||
|
}
|
||||||
|
func _maxDepth1(_ root: TreeNode?) -> Int {
|
||||||
|
if root == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
let leftDepth = _maxDepth1(root!.left)
|
||||||
|
let rightDepth = _maxDepth1(root!.right)
|
||||||
|
return 1 + max(leftDepth, rightDepth)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 层序
|
||||||
|
func maxDepth(_ root: TreeNode?) -> Int {
|
||||||
|
guard let root = root else {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var queue = [TreeNode]()
|
||||||
|
queue.append(root)
|
||||||
|
var res: Int = 0
|
||||||
|
while !queue.isEmpty {
|
||||||
|
res += 1
|
||||||
|
for _ in 0 ..< queue.count {
|
||||||
|
let node = queue.removeFirst()
|
||||||
|
if let left = node.left {
|
||||||
|
queue.append(left)
|
||||||
|
}
|
||||||
|
if let right = node.right {
|
||||||
|
queue.append(right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
>N叉树最大深度
|
||||||
|
```swift
|
||||||
|
// 递归
|
||||||
|
func maxDepth(_ root: Node?) -> Int {
|
||||||
|
guard let root = root else {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var depth = 0
|
||||||
|
for node in root.children {
|
||||||
|
depth = max(depth, maxDepth(node))
|
||||||
|
}
|
||||||
|
return depth + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迭代-层序遍历
|
||||||
|
func maxDepth1(_ root: Node?) -> Int {
|
||||||
|
guard let root = root else {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var depth = 0
|
||||||
|
var queue = [Node]()
|
||||||
|
queue.append(root)
|
||||||
|
while !queue.isEmpty {
|
||||||
|
let size = queue.count
|
||||||
|
depth += 1
|
||||||
|
for _ in 0 ..< size {
|
||||||
|
let node = queue.removeFirst()
|
||||||
|
for child in node.children {
|
||||||
|
queue.append(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return depth
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<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