Invert Binary Tree

Problem

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

Examples

Example 1:

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

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

Example 2:

Input: root = [3,2,1]

Output: [3,1,2]

Example 3:

Input: root = []

Output: []

Constraints

  • 0 <= The number of nodes in the tree <= 100.
  • -100 <= Node.val <= 100

You should aim for a solution with O(n) time and O(n) space, where n is the number of nodes in the tree.

Solution

We recursively invert the left/right subtrees, then swap left/right pointers

/**
 * 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) {
        // Recursively invert left and right subtrees, then swap current left/right
        std::function<void(TreeNode*)> invert_runner;
        invert_runner = [&](TreeNode *node) {
            // Base case, do nothing
            if (!node) {
                return;
            }
            // Invert left and right subtrees
            invert_runner(node->left);
            invert_runner(node->right);
 
            // Swap left and right subtrees
            std::swap(node->left, node->right);
        };
        invert_runner(root);
        return root;
    }
};