226. Invert Binary Tree
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Trees
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven the root of a binary tree, swap the left and right children at every node so that the entire tree is mirrored, then return the new root.
Approach
- Recurse post-order: first invert the left subtree, then the right subtree, then swap the two children of the current node.
- Because each node is visited exactly once and the swap is O(1), the total work is proportional to the number of nodes.
- The recursion naturally handles null leaves as base cases, making no unnecessary work.
- An iterative BFS/DFS alternative exists but recursion is the most readable for this problem.
#include <algorithm> // std::swap
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr; // base case: empty subtree
// Recursively invert both subtrees first (post-order),
// then mirror the children of the current node.
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right); // mirror at this node
return root;
}
}; Time O(n) Space O(h) where h is the height of the tree (O(log n) balanced, O(n) worst case)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <iostream>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root){
return nullptr;
}
std::swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
// Time: O(N), where N is the number of nodes in the tree, since we visit each node once.
// Space: O(H), where H is the height of the tree, due to the recursion stack.
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.