Reverse Odd Levels of Binary Tree — LeetCode 2415 Python Solution
- Problem
- #2415
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a perfect binary tree, reverse the node values at each odd level of the tree. For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].
Example
- Input
- root = [2,3,5,8,13,21,34]
- Output
- [2,5,3,8,13,21,34]
- Explanation
- The tree has only one odd level.
Python solution
# 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]:
q = deque([root])
i = 0
while q:
if i & 1:
l, r = 0, len(q) - 1
while l < r:
q[l].val, q[r].val = q[r].val, q[l].val
l, r = l + 1, r - 1
for _ in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
q.append(node.right)
i += 1
return rootComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2415. Reverse Odd Levels of Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2415. Reverse Odd Levels of Binary Tree?
- LeetCode 2415. Reverse Odd Levels of Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2415. Reverse Odd Levels of Binary Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2415. Reverse Odd Levels of Binary Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2415. Reverse Odd Levels of Binary Tree cover?
- LeetCode 2415. Reverse Odd Levels of Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.