Skip to content

Commit

Permalink
添加 104.二叉树的最大深度 Swift版本
Browse files Browse the repository at this point in the history
  • Loading branch information
qxuewei committed Jan 11, 2022
1 parent d061c16 commit bc710f2
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions problems/0104.二叉树的最大深度.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>

0 comments on commit bc710f2

Please sign in to comment.