Back to solutions
Invert Binary Tree
EasyBinary TreesInvert a binary tree by swapping the left and right child of every node.
Constraints
- 0 <= nodes <= 100
- -100 <= Node.val <= 100
Recursive swap
Time O(n)Space O(h) recursion depth
Swap the children of the current node, then recursively invert each subtree.
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}