LeetCode 226: Invert Binary Tree Solution
Master LeetCode problem 226 (Invert Binary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
226. Invert Binary Tree
Problem Explanation
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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 226 (Invert Binary Tree)?
This page provides optimized solutions for LeetCode problem 226 (Invert Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 226 (Invert Binary Tree)?
The time complexity for LeetCode 226 (Invert Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 226 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 226 in Java, C++, or Python.