LeetCode 226: Invert Binary Tree
Problem Description
Explanation
To invert a binary tree, we swap the left and right children of every node in the tree recursively starting from the root. This can be done using a simple depth-first search (DFS) algorithm. The base case is when we reach a leaf node where we don't have any children to swap.
Algorithm:
- If the root is null, return null.
- Recursively call invertTree function on the left and right subtrees.
- Swap the left and right children of the current root.
- Return the modified root.
Time Complexity: O(n) where n is the number of nodes in the binary tree. Space Complexity: O(n) for the recursive call stack.
Solutions
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;
}
}
Related LeetCode Problems
Loading editor...