Prompt:

You are given the root of a binary tree root. Invert the binary tree and return its root.

Example 1:

Input: root = [1,2,3,4,5,6,7]
 
Output: [1,3,2,7,6,5,4]

Solution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) 
    {
        //null check aka the base case
        if(root == nullptr) 
        {
            return root;
        }
        else
        {
            //swap the right and the left
            TreeNode* temp = root->left;
            root->left = root->right;
            root->right = temp;
 
            //make the invert on both the left and the right tree
            invertTree(root->left);
            invertTree(root->right);
        }
 
        return root;
 
    }
};
 

Explanation:

So the way a tree works is its similar to a linked list, but instead of a single pointer to another node, there exists two pointers, the one to the right is always larger than the one to the left but smaller than the current head node.

With this out of the way, if you want to invert this, so that way the value on the left is always larger than that of the right, what you can do is use recursion, which recursion in general is the best way of traversal on these trees.

So to invert this tree here the best thing to do is first check to see if the node is null as the base case, and then what you do if the node is not null, then you do the regular swap like you do in whatever, with a temp value assign the change, assign the temp to the thing that was overwritten blah blah blah.

Once you have made this change you invert the subsequent left and right tree, sort of to how something like how the breadth first search algorithm ends up working, this way you have an O(n) time complexity because you touch each node and do the swap once, and then O(h) space which is just the recursion space on the program’s stack