Data Structures: BST DFS using iteration rather than recursion

This commit is contained in:
Manish 2023-09-01 18:17:58 +10:00
parent 833ef203d9
commit 27feb10c27

View File

@ -14,12 +14,24 @@ function BinarySearchTree() {
return null; return null;
} }
const values = []; const values = [];
const traverse = (node) => { const stack = [{ node: this.root, stage: "left" }];
if (node.left !== null) traverse(node.left); while (stack.length) {
values.push(node.value); const { node, stage } = stack[stack.length - 1];
if (node.right !== null) traverse(node.right); if (stage === "left") {
}; stack[stack.length - 1].stage = "node";
traverse(this.root); 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; return values;
}; };
@ -28,12 +40,24 @@ function BinarySearchTree() {
return null; return null;
} }
const values = []; const values = [];
const traverse = (node) => { const stack = [{ node: this.root, stage: "node" }];
values.push(node.value); while (stack.length) {
if (node.left !== null) traverse(node.left); const { node, stage } = stack[stack.length - 1];
if (node.right !== null) traverse(node.right); if (stage === "node") {
}; stack[stack.length - 1].stage = "left";
traverse(this.root); 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; return values;
}; };
@ -42,12 +66,24 @@ function BinarySearchTree() {
return null; return null;
} }
const values = []; const values = [];
const traverse = (node) => { const stack = [{ node: this.root, stage: "left" }];
if (node.left !== null) traverse(node.left); while (stack.length) {
if (node.right !== null) traverse(node.right); const { node, stage } = stack[stack.length - 1];
values.push(node.value); if (stage === "left") {
}; stack[stack.length - 1].stage = "right";
traverse(this.root); 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; return values;
}; };
// Only change code above this line // Only change code above this line