A recent edit to an answer bubbled this older question to the top, and I didn't see any simple answer that treated the data immutably. So here is one quick function:
const invertTree = (t) =>
t === null ? null : new TreeNode (t .val, invertTree (t .right), invertTree (t .left))
const tree = new TreeNode (4, new TreeNode (2, new TreeNode (1), new TreeNode (3)), new TreeNode (7, new TreeNode (6), new TreeNode (9)))
const inverted = invertTree (tree)
// Note that the original is not mutated:
console .log ('Original: ', JSON .stringify (tree, null, 4))
console .log ('Inverted: ', JSON .stringify (inverted, null, 4))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script>function TreeNode (val, left, right) {this .val = (val === undefined ? 0 : val); this .left = (left === undefined ? null : left); this .right = (right === undefined ? null : right)}</script>
In our base case, the node is null and we return null. Otherwise we construct a new node with the same val, and with recursive calls to invertTree passing the right node and the left node in that order so that the new tree has them swapped.
If it were up to me, I would not use a constructor function (nor a class) for this but a simple data constructor:
const node = (val, left, right) => ({val, left: left || null, right: right || null})
const invertTree = (t) =>
t == null ? null : node (t .val, invertTree (t .right), invertTree (t .left))
const tree = node (4, node (2, node (1), node (3)), node (7, node (6), node (9)))
const inverted = invertTree (tree)
console .log ('Original: ', JSON .stringify (tree, null, 4))
console .log ('Inverted: ', JSON .stringify (inverted, null, 4))
.as-console-wrapper {max-height: 100% !important; top: 0}
[root.left, root.right] = [root.right, root.left]then do same for children