Invert Binary Tree
Invert Binary Tree is a easy trees & bst problem solved with the recursion pattern.
The best approach, recursive, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from iterative (bfs) up.
Problem
Mirror a binary tree, swapping left and right children at every node, and return its root.
Examples
Example 1
- Input
root = [4, 2, 7, 1, 3, 6, 9]- Output
[4, 7, 2, 9, 6, 3, 1]
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to100nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 2 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Iterative (BFS) | O(n) | O(w) |
| Recursive | O(n) | O(h) |
1Iterative (BFS)
O(n)O(w)Visit nodes with a queue and swap each node's children.
- Poll, swap left and right, enqueue the non-null children.
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode n = q.poll();
TreeNode t = n.left; n.left = n.right; n.right = t;
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
return root;
}
}class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
q = deque([root])
while q:
n = q.popleft()
n.left, n.right = n.right, n.left
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
return rootclass Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* n = q.front(); q.pop();
TreeNode* t = n->left; n->left = n->right; n->right = t;
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
return root;
}
};function invertTree(root) {
if (root === null) return null;
const q = [root];
let head = 0;
while (head < q.length) {
const n = q[head++];
const t = n.left; n.left = n.right; n.right = t;
if (n.left !== null) q.push(n.left);
if (n.right !== null) q.push(n.right);
}
return root;
}2Recursive
O(n)O(h)Invert both subtrees and attach them to the opposite sides.
- if root == null return null.
- left = invert(root.left); right = invert(root.right).
- root.left = right; root.right = left.
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode left = invertTree(root.left), right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
left, right = self.invertTree(root.left), self.invertTree(root.right)
root.left = right
root.right = left
return rootclass Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
};function invertTree(root) {
if (root === null) return null;
const left = invertTree(root.left), right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}Edge cases to test
- Empty tree
- Single node
Hints
Hint 1
Swap the two children of every node. The order you visit nodes in does not matter.
FAQ
What is the best time complexity for Invert Binary Tree?
Recursive runs in O(n) time and O(h) extra space.
Which pattern does Invert Binary Tree use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Invert Binary Tree?
Yes. Iterative (BFS) takes O(n) time and O(w) space. Visit nodes with a queue and swap each node's children.
Which edge cases should I test for Invert Binary Tree?
Empty tree; Single node.