-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-Binary-Tree-Level-Order-Traversal.swift
55 lines (45 loc) · 1.21 KB
/
102-Binary-Tree-Level-Order-Traversal.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// 102-Binary-Tree-Level-Order-Traversal.swift
// algorithm
//
// Created by Lugick Wang on 2020/3/30.
// Copyright © 2020 Lugick Wang. All rights reserved.
//
import Foundation
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else {
return [[Int]]()
}
var data = [[Int]]()
var tempArray = [TreeNode]()
tempArray.append(root)
while tempArray.count > 0 {
var temp = [Int]()
for _ in 0..<tempArray.count {
let node = tempArray.removeFirst()
temp.append(node.val)
if let left = node.left {
tempArray.append(left)
}
if let right = node.right {
tempArray.append(right)
}
}
print(temp)
data.append(temp)
}
print(data)
return data
}
}