Invert Binary Tree
Easy
TreeDFSBFS
Problem
Given the root of a binary tree, invert it (mirror image) and return the root.
Example 1
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2
Input: root = [2,1,3]
Output: [2,3,1]
Example 3
Input: root = []
Output: []
Constraints
- 0 ≤ number of nodes ≤ 100
- −100 ≤ Node.val ≤ 100
Approach — Tree Traversal
This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def invertTree(self, root):
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
Java
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Invert Binary Tree interactively → ← All solutions