Logo for ammarahmed.ca
Easy
Dec 23, 2025
#binary-tree
#bfs

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

1Input: root = [4,2,7,1,3,6,9] 2Output: [4,7,2,9,6,3,1]

Example 2:

1Input: root = [2,1,3] 2Output: [2,3,1]

Example 3:

1Input: root = [] 2Output: []
  • The number of nodes in the tree is in the range [0, 100].
    • -100 <= Node.val <= 100

      Constraints:

      Notes

      Intuition

      Inverting a tree means swapping every node's left and right children. We can traverse the tree using BFS (or DFS) and perform the swap at each node.

      Implementation

      Handle the empty tree case first. Initialize a queue with the root. For each node dequeued, swap its left and right children. Then enqueue any non-null children to continue the traversal. Return the original root reference (now pointing to the inverted tree).

      Edge-cases

      An empty tree (null root) should return null immediately. The algorithm handles single-node trees naturally.

      • Time: O(n) — visit each node once
        • Space: O(n) — queue holds up to n/2 nodes at the widest level

          Complexity

          Solution

          1from typing import Deque, Optional 2from lcutils import TreeNode 3from collections import deque 4 5# Definition for a binary tree node. 6# class TreeNode: 7# def __init__(self, val=0, left=None, right=None): 8# self.val = val 9# self.left = left 10# self.right = right 11class Solution: 12 def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 13 if root is None: 14 return root 15 q: Deque[TreeNode] = deque([root]) 16 17 while q: 18 node = q.popleft() 19 node.right, node.left = node.right, node.left 20 if node.left: 21 q.append(node.left) 22 if node.right: 23 q.append(node.right) 24 return root 25 26 27 28if __name__ == "__main__": 29 # Include one-off tests here or debugging logic that can be run by running this file 30 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 31 solution = Solution() 32