Skip to content

Instantly share code, notes, and snippets.

@kottenator
Created March 1, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kottenator/ea5aec9e89d69ec522d35383ee8f2171 to your computer and use it in GitHub Desktop.
Save kottenator/ea5aec9e89d69ec522d35383ee8f2171 to your computer and use it in GitHub Desktop.
In-order traverse without recursion
/**
* Binary tree in-order traversal.
*
* How would look this simple, straightforward algorithm without recursion?
* I don't like recursion, that's one of my attempts to avoid it.
*/
function traverseInOrderNoRecursion(t) {
if (!t) {
return [];
}
let waitingNodes = [[t, 0]];
let visitedNodes = [];
let values = [];
while (waitingNodes.length) {
let [node, depth] = waitingNodes.pop();
visitedNodes.push([node, depth]);
if (node.right) {
waitingNodes.push([node.right, depth + 1]);
}
if (node.left) {
waitingNodes.push([node.left, depth + 1]);
} else {
let maxWaitingNodeDepth = waitingNodes.length ? waitingNodes[waitingNodes.length - 1][1] : 0;
while (visitedNodes.length && visitedNodes[visitedNodes.length - 1][1] >= maxWaitingNodeDepth - 1) {
values.push(visitedNodes.pop()[0].value);
}
}
}
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment