-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree_Zigzag_Level_Order_Traversal.py
77 lines (60 loc) · 1.58 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
"""
from collections import deque
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def zigzagLevelOrder(self, root):
if root == None:
return []
queue = deque([root])
direction = True
result = []
while(len(queue) > 0):
current_level_size = len(queue)
current_level = deque([])
for i in range(current_level_size):
current_node = queue.popleft()
#add current node children to be visited
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
#add visited ndoes in zigzag style
if direction == True: # from left to right
current_level.append(current_node.val)
else: # from right to left
current_level.appendleft(current_node.val)
#save current level
result.append(list(current_level))
#reverse direction
direction = not direction
return result
s = Solution()
root = TreeNode(1)
left = TreeNode(2)
right = TreeNode(3)
root.left = left ; root.right=right
left.right = TreeNode(4) ; right.right = TreeNode(5)
print s.zigzagLevelOrder(root)