-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Zigzag Level Order Traversal.py
55 lines (40 loc) · 1.7 KB
/
Binary Tree Zigzag Level Order Traversal.py
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
50
51
52
53
54
55
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
# If root is empty, return an empty list
if root is None:
return []
# If root is by itself, return itself
if root.left is None and root.right is None:
return [[root.val]]
# Create lists
queue = [root]
finalList = list()
leftToRight = True
# Iterate queue
while len(queue) != 0:
# Iterate queue
nodesOnLevel = list()
for idx in range(len(queue)):
node = queue.pop(0)
# Add children to queue if they exist
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# Save children to other list as well
# NOTE: Must be saved right-left or left-right based on boolean variable
if leftToRight:
nodesOnLevel.append(node.val)
else:
nodesOnLevel.insert(0, node.val)
# Add nodes that were visited to finalList
finalList.append(nodesOnLevel)
leftToRight = not leftToRight
return finalList