From d5dd37d94c7e8209916e68ff751067fd53b646c3 Mon Sep 17 00:00:00 2001 From: Manish Date: Wed, 6 Sep 2023 14:23:43 +1000 Subject: [PATCH] Data Structures: Invert a Binary Tree --- Data Structures/bstInvert.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Data Structures/bstInvert.js diff --git a/Data Structures/bstInvert.js b/Data Structures/bstInvert.js new file mode 100644 index 0000000..25531b1 --- /dev/null +++ b/Data Structures/bstInvert.js @@ -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 +}