From 27feb10c27ca6afec21035127e798a55662ddac0 Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 1 Sep 2023 18:17:58 +1000 Subject: [PATCH] Data Structures: BST DFS using iteration rather than recursion --- Data Structures/bstDFS.js | 72 +++++++++++++++++++++++++++++---------- 1 file changed, 54 insertions(+), 18 deletions(-) diff --git a/Data Structures/bstDFS.js b/Data Structures/bstDFS.js index 903eb8e..6295a59 100644 --- a/Data Structures/bstDFS.js +++ b/Data Structures/bstDFS.js @@ -14,12 +14,24 @@ function BinarySearchTree() { 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); + const stack = [{ node: this.root, stage: "left" }]; + while (stack.length) { + const { node, stage } = stack[stack.length - 1]; + if (stage === "left") { + stack[stack.length - 1].stage = "node"; + if (node.left !== null) { + stack.push({ node: node.left, stage: "left" }); + } + } else if (stage === "node") { + stack[stack.length - 1].stage = "right"; + values.push(node.value); + } else if (stage === "right") { + stack.pop(); + if (node.right !== null) { + stack.push({ node: node.right, stage: "left" }); + } + } + } return values; }; @@ -28,12 +40,24 @@ function BinarySearchTree() { 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); + const stack = [{ node: this.root, stage: "node" }]; + while (stack.length) { + const { node, stage } = stack[stack.length - 1]; + if (stage === "node") { + stack[stack.length - 1].stage = "left"; + values.push(node.value); + } else if (stage === "left") { + stack[stack.length - 1].stage = "right"; + if (node.left !== null) { + stack.push({ node: node.left, stage: "node" }); + } + } else if (stage === "right") { + stack.pop(); + if (node.right !== null) { + stack.push({ node: node.right, stage: "node" }); + } + } + } return values; }; @@ -42,12 +66,24 @@ function BinarySearchTree() { 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); + const stack = [{ node: this.root, stage: "left" }]; + while (stack.length) { + const { node, stage } = stack[stack.length - 1]; + if (stage === "left") { + stack[stack.length - 1].stage = "right"; + if (node.left !== null) { + stack.push({ node: node.left, stage: "left" }); + } + } else if (stage === "right") { + stack[stack.length - 1].stage = "node"; + if (node.right !== null) { + stack.push({ node: node.right, stage: "left" }); + } + } else if (stage === "node") { + stack.pop(); + values.push(node.value); + } + } return values; }; // Only change code above this line