Given a binary tree, invert it such that the left and right children of every node are swapped.
Breadth-First Search (BFS)
root
is None
, returning None
if so.root
for level-order traversal.root
.Consider the following binary tree:
4
/ \
2 7
/ \ / \
1 3 6 9
After inverting:
4
/ \
7 2
/ \ / \
9 6 3 1
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return
queue = [root]
while queue:
node = queue.pop(0)
# Swap left and right children
temp = node.left
node.left = node.right
node.right = temp
# Enqueue left and right children if they exist
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root