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) {
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); values.push(node.value);
if (node.right !== null) traverse(node.right); } else if (stage === "right") {
}; stack.pop();
traverse(this.root); 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" }];
while (stack.length) {
const { node, stage } = stack[stack.length - 1];
if (stage === "node") {
stack[stack.length - 1].stage = "left";
values.push(node.value); values.push(node.value);
if (node.left !== null) traverse(node.left); } else if (stage === "left") {
if (node.right !== null) traverse(node.right); stack[stack.length - 1].stage = "right";
}; if (node.left !== null) {
traverse(this.root); 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];
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); values.push(node.value);
}; }
traverse(this.root); }
return values; return values;
}; };
// Only change code above this line // Only change code above this line