添加 Swift 代码实现

This commit is contained in:
frank-tian 2021-07-19 23:13:17 +08:00
parent 8920c2d83a
commit 9116bc63ce

View File

@ -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
}
}
```
时间复杂度On 空间复杂度On
大家如果吃透了二叉树的层序遍历的话可以顺手把下面几道题目解决掉思路一致甚至都不用拐弯