Skip to content

Commit

Permalink
[Tree] Optimize solution to Binary Tree Zigzag Level Order Traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Sep 10, 2018
1 parent 20ef690 commit 1163c3d
Showing 1 changed file with 9 additions and 23 deletions.
32 changes: 9 additions & 23 deletions Tree/BinaryTreeZigzagLevelOrderTraversal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,19 @@

class BinaryTreeZigzagLevelOrderTraversal {
func zigzagLevelOrder(root: TreeNode?) -> [[Int]] {
var res = [[Int]](), queue = [TreeNode](), isReverse = false

if let root = root {
queue.append(root)
guard let root = root else {
return [[Int]]()
}

while !queue.isEmpty {
let size = queue.count
var level = [Int]()

for _ in 0..<size {
let node = queue.removeFirst()

// add val
level.insert(node.val, at: isReverse ? 0 : level.count)

// add TreeNodes in next level
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
var res = [[Int]](), isReverse = false, nodeQ = [root]

while !nodeQ.isEmpty {
let currentLevel = nodeQ.map { $0.val }
res.append(isReverse ? currentLevel.reversed() : currentLevel)

res.append(level)
isReverse = !isReverse

nodeQ = nodeQ.flatMap { [$0.left, $0.right].compactMap { $0 } }
}

return res
Expand Down

0 comments on commit 1163c3d

Please sign in to comment.