-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzigzag_bst.rb
46 lines (40 loc) · 1 KB
/
zigzag_bst.rb
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
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {TreeNode} root
# @return {Integer[][]}
def zigzag_level_order(root)
return [] unless root
ans = []
q = []
q << root if root
q << nil
level_list = []
is_order_left = true
while !q.empty?
cur = q.shift
if cur
# add val to level list - to beginning or end depending on level
is_order_left ? level_list.push(cur.val) : level_list.unshift(cur.val)
# add children to queue
q.push(cur.left) if cur.left
q.push(cur.right) if cur.right
else
# finish scan of the level
ans << level_list
level_list = []
if !q.empty?
q.push(nil)
is_order_left = !is_order_left
end
end
end
ans
end