226. Invert Binary Tree

Solved at: Jul 14, 2025 🇲🇽
  var invertTree = function (root) {
    function invert(node) {
        if (node === null) {
            return;
        }
        let temp = node.left;
        node.left = node.right;
        node.right = temp;
        invert(node.left);
        invert(node.right);
    }
    invert(root);
    return root;
};
  var invertTree = function (root) {
    function invert(node) { 
        if (node === null) { //First we always check if the node is null
            return; // Here's the end game, if the node is null then we have nothing else to do, we return.
        }
        let temp = node.left; // We need to create a temporal copy of one of the nodes.
        node.left = node.right; //Swap left for right
        node.right = temp; // Swap right for temporal
        invert(node.left); // Let's repeat the process with left...
        invert(node.right); // And Right
    }
    invert(root);
    return root;
};