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;
}
const values = [];
const traverse = (node) => {
if (node.left !== null) traverse(node.left);
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);
if (node.right !== null) traverse(node.right);
};
traverse(this.root);
} 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) => {
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);
if (node.left !== null) traverse(node.left);
if (node.right !== null) traverse(node.right);
};
traverse(this.root);
} 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);
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);
};
traverse(this.root);
}
}
return values;
};
// Only change code above this line