-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzag_level_order.py
More file actions
54 lines (37 loc) · 1.25 KB
/
zigzag_level_order.py
File metadata and controls
54 lines (37 loc) · 1.25 KB
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
from collections import deque
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).resolve().parent.parent))
from binary_tree import create_binary_tree
class Solution:
def zigzagLevelOrder(self, root):
if root is None:
return []
result = []
queue = deque([root])
starts_left = True
while queue:
level_order = deque()
for _ in range(len(queue)):
curr_node = queue.popleft()
if starts_left:
level_order.append(curr_node.val)
else:
level_order.appendleft(curr_node.val)
if curr_node.left:
queue.append(curr_node.left)
if curr_node.right:
queue.append(curr_node.right)
starts_left = not starts_left
result.append(list(level_order))
return result
# Time Complexity: O(n)
# Space Complexity: O(n)
if __name__ == "__main__":
solution = Solution()
root = [3, 9, 20, None, None, 15, 7]
bt = create_binary_tree(root)
result = solution.zigzagLevelOrder(bt)
assert result == [[3], [20, 9], [15, 7]]
print("Test Case 1 Passed!")
print(result)