Logo for ammarahmed.ca
Easy
Oct 06, 2025
#binary-tree

226. Invert Binary Tree

Problem

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] 3

Example 2:

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

Example 3:

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

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
    • -100 <= Node.val <= 100

      Approach

      To solve this problem, we can use a recursive approach.

      Our base case will be when the node has neither left or right children or the node itself is null, return here.

      Otherwise, we set the left side to the right side and the right side to left side and then call the function on both left and right

      Complexity

      Time: O(n)

      Iterate through the whole tree

      Space: O(n)

      For the recursive calls.

      Solution

      1func invertTree(root *TreeNode) *TreeNode { 2 if root == nil || (root.Left == nil && root.Right == nil) { 3 return root 4 } 5 6 temp := root.Right 7 root.Right = invertTree(root.Left) 8 root.Left = invertTree(temp) 9 return root 10} 11