forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeLevelOrderTraversalII.swift
55 lines (48 loc) · 1.45 KB
/
BinaryTreeLevelOrderTraversalII.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
/**
* Question Link: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
* Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
*
* Note: use method insertAtIndex to add each level to final result
*
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* 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 BinaryTreeLevelOrderTraversalII {
func levelOrderBottom(root: TreeNode?) -> [[Int]] {
var res = [[Int]]()
var queue = [TreeNode]()
if let root = root {
queue.append(root)
}
while queue.count > 0 {
var size = queue.count
var level = [Int]()
for _ in 1...size {
let node = queue[0]
queue.removeAtIndex(0)
// add val
level.append(node.val)
// add TreeNodes in next level
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
res.insert(level, atIndex:0)
}
return res
}
}