Data Structures: Invert a Binary Tree

This commit is contained in:
Manish 2023-09-06 14:23:43 +10:00
parent 1f54446eda
commit d5dd37d94c

View 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
}