Invert Binary Tree

Recursively swap each node's children — a four-line classic.

Easy
Time O(n) Space O(h)
LeetCode
2 min read
tree dfs

Problem#

Given the root of a binary tree, invert it (left subtree becomes right and vice versa at every node) and return its root.

Examples#

  • [4,2,7,1,3,6,9][4,7,2,9,6,3,1]
  • [2,1,3][2,3,1]
  • [][]

Constraints#

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

Approach#

Recursively invert left and right subtrees, then swap them.

Solution#

Invert Binary Tree
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
TreeNode* l = invertTree(root->left);
TreeNode* r = invertTree(root->right);
root->left = r;
root->right = l;
return root;
}
};

Editorial#

Each node is visited exactly once. The swap happens after recursion so subtree pointers are already inverted — equivalent to swapping first then recursing, both correct.

Complexity#

  • Time: O(n).
  • Space: O(h) recursion stack.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.