226. Invert Binary Tree LeetCode Solution

In this guide, you will get 226. Invert Binary Tree LeetCode Solution with the best time and space complexity. The solution to Invert Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Invert Binary Tree solution in C++
  4. Invert Binary Tree solution in Java
  5. Invert Binary Tree solution in Python
  6. Additional Resources
226. Invert Binary Tree LeetCode Solution image

Problem Statement of Invert Binary Tree

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 <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(h)

226. Invert Binary Tree LeetCode Solution in C++

class Solution {
 public:
  TreeNode* invertTree(TreeNode* root) {
    if (root == nullptr)
      return nullptr;

    TreeNode* const left = root->left;
    TreeNode* const right = root->right;
    root->left = invertTree(right);
    root->right = invertTree(left);
    return root;
  }
};
/* code provided by PROGIEZ */

226. Invert Binary Tree LeetCode Solution in Java

class Solution {
  public TreeNode invertTree(TreeNode root) {
    if (root == null)
      return null;

    TreeNode left = root.left;
    TreeNode right = root.right;
    root.left = invertTree(right);
    root.right = invertTree(left);
    return root;
  }
}
// code provided by PROGIEZ

226. Invert Binary Tree LeetCode Solution in Python

class Solution:
  def invertTree(self, root: TreeNode | None) -> TreeNode | None:
    if not root:
      return None

    left = root.left
    right = root.right
    root.left = self.invertTree(right)
    root.right = self.invertTree(left)
    return root
# code by PROGIEZ

Additional Resources

See also  2788. Split Strings by Separator LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.