226. Invert Binary Tree
At a Glance
- Topic: Binary Tree
- Pattern: DFS
- Difficulty: Easy
- LeetCode: 226
Problem Statement
Given the root of a binary tree, invert the tree, and return its 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:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100Approach & Solution Steps
Use a recursive DFS approach. For each node, swap its left and right children, then recursively call the function on the left and right subtrees.
Optimal JS Solution
function invertTree(root) {
if (!root) return null;
const temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?