Created
March 1, 2018 13:54
-
-
Save kottenator/ea5aec9e89d69ec522d35383ee8f2171 to your computer and use it in GitHub Desktop.
In-order traverse without recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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