Leetcode 226. Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
Example:
Input: Root of the Binary Tree
Output: Root of the Inverted Binary Tree
null
).root
is null
), return null
.We can use recursion to invert the binary tree. The function will recursively invert the left and right subtrees and then swap them.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// Base case: if the tree is empty, return null
if (root == null) {
return null;
}
// Recursively invert the left and right subtrees
TreeNode leftInverted = invertTree(root.left);
TreeNode rightInverted = invertTree(root.right);
// Swap the left and right children
root.left = rightInverted;
root.right = leftInverted;
// Return the current root
return root;
}
}
This recursive approach ensures that each node is visited and its left and right children are swapped, resulting in the inversion of the binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?