Header Ad

Leetcode Invert Binary Tree problem solution

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;
}


Post a Comment

0 Comments