Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal

Binary Search Version - 36ms

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
queue = [root]
res = []
level = 0
while queue:
level += 1
temp = []
tempq = []
for node in queue:
temp.append(node.val)
if node.left:
tempq.append(node.left)
if node.right:
tempq.append(node.right)
queue = tempq
if level % 2 == 0 :
temp = temp[::-1]
res.append(temp)
return res

leet code