2018-10-12 15:37:13 -04:00
---
title: Invert a Binary Tree
---
2019-07-24 00:59:27 -07:00
# Invert a Binary Tree
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Hints
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
### Hint 1
2019-06-20 13:28:37 -04:00
Create a invert(node = this.root) method in the BinarySearchTree constructor function.
## Hint: 2
Try to use recursion and think of a base case.
2019-07-24 00:59:27 -07:00
---
## Solutions
2019-06-20 13:28:37 -04:00
2019-07-24 00:59:27 -07:00
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2019-06-20 13:28:37 -04:00
```js
2019-07-24 00:59:27 -07:00
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
2019-06-20 13:28:37 -04:00
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
this.invert = function(node = this.root) {
if (node) {
const temp = node.left;
node.left = node.right;
node.right = temp;
this.invert(node.left);
this.invert(node.right);
}
return node;
2019-07-24 00:59:27 -07:00
};
// change code above this line
2019-06-20 13:28:37 -04:00
}
```
< a href = 'https://repl.it/repls/SereneScholarlyAnalyst' target = '_blank' rel = 'nofollow' > Run Code< / a >
2019-07-24 00:59:27 -07:00
#### Code Explanation
2019-06-20 13:28:37 -04:00
* Using recursion will allow you to traverse each node once and the only extra memory used is the auxiliary temp variable that enables you to swap. You keep swapping the left and right pointers of a node until you reach the leaves which will not do anything as the left and right of them are null references.
2019-07-24 00:59:27 -07:00
< / details >