Data Structures: Invert a Binary Tree
This commit is contained in:
parent
1f54446eda
commit
d5dd37d94c
27
Data Structures/bstInvert.js
Normal file
27
Data Structures/bstInvert.js
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/invert-a-binary-tree
|
||||||
|
|
||||||
|
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
|
||||||
|
function Node(value) {
|
||||||
|
this.value = value;
|
||||||
|
this.left = null;
|
||||||
|
this.right = null;
|
||||||
|
}
|
||||||
|
function BinarySearchTree() {
|
||||||
|
this.root = null;
|
||||||
|
// Only change code below this line
|
||||||
|
this.invert = () => {
|
||||||
|
if (this.root === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const stack = [this.root];
|
||||||
|
while (stack.length) {
|
||||||
|
const node = stack.pop();
|
||||||
|
const tmp = node.left;
|
||||||
|
node.left = node.right;
|
||||||
|
node.right = tmp;
|
||||||
|
if (node.left !== null) stack.push(node.left);
|
||||||
|
if (node.right !== null) stack.push(node.right);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Only change code above this line
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user