forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeVerticalOrderTraversal.swift
49 lines (43 loc) · 1.53 KB
/
BinaryTreeVerticalOrderTraversal.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-vertical-order-traversal/
* Primary idea: Use queues to hold TreeNode and column level, and a dictionary to
* map column with its correspond TreeNode vals
*
* 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 BinaryTreeVerticalOrderTraversal {
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else {
return [[Int]]()
}
var orderToVals = [0: [root.val]], nodes = [(root, 0)]
while !nodes.isEmpty {
let size = nodes.count
for _ in 0..<size {
let (node, order) = nodes.removeFirst()
if let left = node.left {
orderToVals[order - 1, default: []].append(left.val)
nodes.append((left, order - 1))
}
if let right = node.right {
orderToVals[order + 1, default: []].append(right.val)
nodes.append((right, order + 1))
}
}
}
return orderToVals.sorted { $0.key < $1.key }.map { $0.value }
}
}