Invert Binary Tree
The key idea
Inverting a tree just means swapping the left and right child of every node. Solve it the same way you would describe it recursively: swap the two children of the current node, then invert each of the two subtrees. The node values never change — only the links between parents and children do.
Problem
You are given the root of a binary tree. Invert the tree and return its root.
To invert a binary tree, you turn it into its mirror image: at every node, its left subtree and right subtree are swapped. The values stored in the nodes stay the same — only the left/right position of each child changes.
Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Examples
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Input: root = [2,1,3]
Output: [2,3,1]
Input: root = []
Output: []
Complexity
Time: O(n) Space: O(h)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Tree / Recursion problems
- Balanced Binary TreeEASY
- Binary Tree CamerasHARD
- Binary Tree Inorder TraversalEASY
- Binary Tree Maximum Path SumHARD
- Binary Tree PathsEASY
- Binary Tree Postorder TraversalEASY
- Binary Tree Preorder TraversalEASY
- House Robber IIIMEDIUM
- Construct Binary Tree from Inorder and Postorder TraversalMEDIUM
- Construct Binary Tree from Preorder and Inorder TraversalMEDIUM
- Convert BST to Greater TreeMEDIUM
- Count Complete Tree NodesEASY