# 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;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/invert-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
