Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Invert Binary Tree problem solution

YASH PAL, 31 July 2024

In this Leetcode Invert Binary Tree problem solution, we have given the root of a binary tree, invert the tree, and return its root.

Leetcode Invert Binary Tree problem solution

Problem solution in Python.

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root == None:
            return
        left = root.left
        right = root.right
        root.left, root.right = right, left
        self.invertTree(root.left)
        self.invertTree(root.right)
        
        return root

Problem solution in Java.

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
        
    }

Problem solution in C++.

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
        {
            return NULL;
        }
        
        std::swap(root->left, root->right);

        TreeNode *l = invertTree(root->left);
        TreeNode *r = invertTree(root->right);
        
        return root;
    }
};

Problem solution in C.

struct TreeNode* invertTree(struct TreeNode* root){
        if (root != NULL) {
            struct TreeNode *tmp;
            tmp = root->right != NULL ? invertTree(root->right) : root->right;
            root->right = root->left != NULL ? invertTree(root->left) : root->left;
            root->left = tmp;
        }
    return root;
}

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes