Algo-Sim › Binary Trees & BST
Invert Binary Tree
Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Mirror the tree: invert both subtrees, then swap them. Every node is visited once.
Problem
Mirror a binary tree: swap the left and right child of every node. Return the root of the inverted tree.
Constraints
- 0 ≤ number of nodes ≤ 100
- -100 ≤ Node.val ≤ 100
Edge cases to test
- Empty tree
- One node
- Only left children
Follow-up questions
- Recursive or iterative?
- Either visits each node once. BFS with a queue avoids deep recursion on a skewed tree.
- How do you check two trees are mirrors?
- Compare left with right recursively (Symmetric Tree, LC 101).
Solution
Java
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;
}Python
def invert_tree(root):
if not root:
return None
left = invert_tree(root.left)
right = invert_tree(root.right)
root.left, root.right = right, left
return rootC++
#include <bits/stdc++.h>
using namespace std;
class 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;
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)