> For the complete documentation index, see [llms.txt](https://algorithm.prettylog.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/invert-binary-tree.md).

# Invert Binary Tree

![](/files/mtKATxZggMLkFmYbQY0V)

* n, n

```jsx
function invertBinaryTree(tree) {
  return invertHelper(tree);
}

function invertHelper(node) {
  if (node === null) {
    return null;
  }

  const left = node.left;
  const right = node.right;

  node.right = invertHelper(node.left); 
  // can not use node.right cuz you loose your reference from above
  node.left = invertHelper(right); 

  return node;
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.invertBinaryTree = invertBinaryTree;
```
