打卡记录
反转二叉树的奇数层(bfs)
链接
class Solution:
def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
q = [root]
flag = 0
while q:
t, q = q, []
if flag:
l, r = 0, len(t) - 1
while l < r:
t[l].val, t[r].val = t[r].val, t[l].val
l += 1
r -= 1
flag ^= 1
for node in t:
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root