freeCodeCamp/Data Structures/bstInvert.js

28 lines
752 B
JavaScript
Raw Normal View History

2023-09-06 06:23:43 +02:00
// 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
}