Created
January 14, 2018 01:32
-
-
Save jinwolf/0add8c3f3e34b34b152799cb45f25554 to your computer and use it in GitHub Desktop.
Postorder binary tree traversal with a single stack
This file contains hidden or 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
class Node { | |
constructor(val) { | |
this.value = val; | |
this.left = null; | |
this.right = null; | |
} | |
} | |
let nodes = [ | |
new Node('a'), //0 | |
new Node('b'), //1 | |
new Node('c'), //2 | |
new Node('d'), //3 | |
new Node('e'), //4 | |
new Node('f'), //5 | |
new Node('g'), | |
new Node('h'), | |
new Node('i'), | |
]; | |
console.log('======================= post order iterable'); | |
function traversePostOrder_itr(node) { | |
const stack = []; | |
let popped = null; | |
while(true) { | |
if (node !== null) { | |
stack.push(node); | |
node = node.left; | |
} else { | |
if (stack.length === 0) { | |
break; | |
} | |
// check the right node | |
let top = stack[stack.length - 1]; | |
if (top.right === null || top.right === popped) { | |
popped = stack.pop(); | |
console.log(popped.value); | |
} else { | |
node = top.right; | |
} | |
} | |
} | |
} | |
traversePostOrder_itr(nodes[5]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment