classSolution:defreverseOddLevels(self, root: Optional[TreeNode])-> Optional[TreeNode]:
d = defaultdict(list)defdfs(node, deep):if node isNone:returnif deep %2==1:
d[deep].append(node)
dfs(node.left, deep +1)
dfs(node.right, deep +1)
dfs(root,0)
i =1whileTrue:if i notin d:break
n =len(d[i])for k inrange(n //2):
d[i][k].val, d[i][n - k -1].val = d[i][n - k -1].val, d[i][k].val
i +=2return root