Skip to content

Commit 414f4be

Browse files
committed
[Tree] Refactor solution to Binary Tree Vertical Order Traversal
1 parent bff4c3e commit 414f4be

File tree

1 file changed

+17
-29
lines changed

1 file changed

+17
-29
lines changed

Tree/BinaryTreeVerticalOrderTraversal.swift

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,42 +20,30 @@
2020

2121
class BinaryTreeVerticalOrderTraversal {
2222
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
23-
var res = [[Int]](), qNodes = [TreeNode](), qVals = [Int]()
24-
var colVals = [Int: [Int]](), minCol = 0, maxCol = 0
25-
23+
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
2624
guard let root = root else {
27-
return res
25+
return [[Int]]()
2826
}
2927

30-
qNodes.append(root)
31-
qVals.append(0)
28+
var orderToVals = [0: [root.val]], nodes = [(root, 0)]
3229

33-
while !qNodes.isEmpty {
34-
let node = qNodes.removeFirst()
35-
let col = qVals.removeFirst()
30+
while !nodes.isEmpty {
31+
let size = nodes.count
3632

37-
if colVals[col] != nil {
38-
colVals[col]!.append(node.val)
39-
} else {
40-
colVals[col] = [node.val]
33+
for _ in 0..<size {
34+
let (node, order) = nodes.removeFirst()
35+
36+
if let left = node.left {
37+
orderToVals[order - 1, default: []].append(left.val)
38+
nodes.append((left, order - 1))
39+
}
40+
if let right = node.right {
41+
orderToVals[order + 1, default: []].append(right.val)
42+
nodes.append((right, order + 1))
43+
}
4144
}
42-
43-
if let left = node.left {
44-
qNodes.append(left)
45-
qVals.append(col - 1)
46-
minCol = min(minCol, col - 1)
47-
}
48-
if let right = node.right {
49-
qNodes.append(right)
50-
qVals.append(col + 1)
51-
maxCol = max(maxCol, col + 1)
52-
}
53-
}
54-
55-
for col in minCol...maxCol {
56-
res.append(colVals[col]!)
5745
}
5846

59-
return res
47+
return orderToVals.sorted { $0.key < $1.key }.map { $0.value }
6048
}
6149
}

0 commit comments

Comments
 (0)