Invert Binary Tree Solution in C++ – LeetCode [Easy]

Problem

Given the root of a binary tree, invert the tree, and return its root.

LeetCode Problem Link

Input

root of a binary tree

Output

Invert the binary tree, and return its root.

Constraints
  • 0 <= Number of Nodes in the Tree ≤ 100
  • -100 <= Value of Nodes ≤ 100
Sample Input
root = [10, 2, 21]
Sample Output
[10, 21, 2]

Code Implementation

class Solution {
public:
    
    void solve (TreeNode *root) {
        if (root == NULL) {
            return;
        }
        
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        
        solve (root->left);
        solve (root->right);   
    }
    
    TreeNode* invertTree(TreeNode* root) {
        solve(root);
        return root;
    }
};

Time Complexity: O(n)
Space Complexity: O(1) (without considering recursive stack)

Leave a Reply

Your email address will not be published. Required fields are marked *