mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 04:46:17 +00:00
添加 Swift 代码实现
This commit is contained in:
parent
8920c2d83a
commit
9116bc63ce
@ -406,6 +406,42 @@ public:
|
||||
};
|
||||
```
|
||||
|
||||
Swift Code:
|
||||
|
||||
```swift
|
||||
class Solution {
|
||||
func levelOrder(_ root: TreeNode?) -> [[Int]] {
|
||||
var res:[[Int]] = []
|
||||
guard root != nil else {
|
||||
return res
|
||||
}
|
||||
var queue:[TreeNode?] = []
|
||||
queue.append(root!)
|
||||
|
||||
while !queue.isEmpty {
|
||||
let size = queue.count
|
||||
var list:[Int] = []
|
||||
|
||||
for i in 0..<size {
|
||||
guard let node = queue.removeFirst() else {
|
||||
continue
|
||||
}
|
||||
if node.left != nil {
|
||||
queue.append(node.left)
|
||||
}
|
||||
if node.right != nil {
|
||||
queue.append(node.right);
|
||||
}
|
||||
list.append(node.val)
|
||||
}
|
||||
res.append(list)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
时间复杂度:O(n) 空间复杂度:O(n)
|
||||
|
||||
大家如果吃透了二叉树的层序遍历的话,可以顺手把下面几道题目解决掉,思路一致,甚至都不用拐弯
|
||||
|
Loading…
Reference in New Issue
Block a user