-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse odd levels of binary tree.py
40 lines (35 loc) · 1.41 KB
/
Reverse odd levels of binary tree.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
# 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 reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# Helper function to perform BFS and reverse old levels
def bfs_and_reverse(node):
queue = [node]
level = 0
while queue:
level_size = len(queue)
current_level = []
next_queue = []
for i in range(level_size):
current_node = queue[i]
current_level.append(current_node)
if current_node.left and current_node.right:
next_queue.append(current_node.left)
next_queue.append(current_node.right)
# Reverse node values at odd levels
if level % 2 == 1:
start, end = 0, len(current_level) - 1
while start < end:
current_level[start].val, current_level[end].val = current_level[end].val, current_level[start].val
start += 1
end -= 1
queue = next_queue
level += 1
bfs_and_reverse(root)
return root