Skip to content

Instantly share code, notes, and snippets.

@drbr
Created December 20, 2016 06:46
Show Gist options
  • Save drbr/1b02eb1486a9e321d3d9e3e6d5578a4e to your computer and use it in GitHub Desktop.
Save drbr/1b02eb1486a9e321d3d9e3e6d5578a4e to your computer and use it in GitHub Desktop.
A simple algorithm for traversing a binary search tree in-order without using recursion.
function traverseTreeInOrder(tree) {
// In the real world, we'd need a more robust solution of storing
// and looking up object IDs. But JavaScript doesn't make that easy.
const visitedNodes = {};
const stack = [ tree ];
while (stack.length > 0) {
let node = stack.pop();
if (!node) {
continue;
}
if (!visitedNodes[node.id]) {
stack.push(node.right);
stack.push(node);
stack.push(node.left);
visitedNodes[node.id] = true;
} else {
visitNode(node);
}
}
}
function visitNode(node) {
console.log(node.id);
}
const SampleTree = {
id: 7,
left: {
id: 4,
left: {
id: 2,
left: { id: 1 },
right: { id: 3 }
},
right: {
id: 6,
left: { id: 5 }
}
},
right: {
id: 8,
right: {
id: 10,
left: { id: 9 },
right: {
id: 11,
right: { id: 12 }
}
}
}
};
traverseTreeInOrder(SampleTree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment