From 833ef203d9cbf266782d645bcc9754addd45b6b1 Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 1 Sep 2023 13:17:06 +1000 Subject: [PATCH] Data Structures: Use Breadth First Search in a Binary Search Tree --- Data Structures/bstDFS.js | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Data Structures/bstDFS.js diff --git a/Data Structures/bstDFS.js b/Data Structures/bstDFS.js new file mode 100644 index 0000000..903eb8e --- /dev/null +++ b/Data Structures/bstDFS.js @@ -0,0 +1,54 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-depth-first-search-in-a-binary-search-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.inorder = () => { + if (this.root === null) { + return null; + } + const values = []; + const traverse = (node) => { + if (node.left !== null) traverse(node.left); + values.push(node.value); + if (node.right !== null) traverse(node.right); + }; + traverse(this.root); + return values; + }; + + this.preorder = () => { + if (this.root === null) { + return null; + } + const values = []; + const traverse = (node) => { + values.push(node.value); + if (node.left !== null) traverse(node.left); + if (node.right !== null) traverse(node.right); + }; + traverse(this.root); + return values; + }; + + this.postorder = () => { + if (this.root === null) { + return null; + } + const values = []; + const traverse = (node) => { + if (node.left !== null) traverse(node.left); + if (node.right !== null) traverse(node.right); + values.push(node.value); + }; + traverse(this.root); + return values; + }; + // Only change code above this line +}