forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinaryTreeRightSideView.swift
49 lines (42 loc) · 1.26 KB
/
BinaryTreeRightSideView.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
/**
* Question Link: https://leetcode.com/problems/binary-tree-right-side-view/
* Primary idea: use a queue to keep TreeNode, and for each level add the last one
* 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 BinaryTreeRightSideView {
func rightSideView(_ root: TreeNode?) -> [Int] {
var res = [Int]()
var nodeQ = [TreeNode]()
if let root = root {
nodeQ.append(root)
}
while nodeQ.count > 0 {
var size = nodeQ.count
for i in 0 ..< size {
let node = nodeQ.removeFirst()
if i + 1 == size {
res.append(node.val)
}
if let left = node.left {
nodeQ.append(left)
}
if let right = node.right {
nodeQ.append(right)
}
}
}
return res
}
}