LeetCode 226: Invert Binary Tree
LeetCode 226 Solution 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.
LeetCode 226 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 226
Improve Your LeetCode 226 Solution
Use the editor below to refine the provided solution for LeetCode 226. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...