forked from OperationCode/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostOrderIterative.js
More file actions
52 lines (34 loc) · 1.17 KB
/
PostOrderIterative.js
File metadata and controls
52 lines (34 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import BinaryTreeNode from './BinaryTreeNode';
import Stack from './../stack/Stack';
export function postOrderIterative(tree,callback){
var node = tree.store;
var st = new Stack();
while (node || !st.isEmpty() )
{
while (node)
{
// Push node's right child and then node to stack.
if (node.right)
st.push(node.right);
st.push(node);
// Set node as node's left child
node = node.left;
}
// Pop an item from stack and set it as node
node = st.pop();
// If the popped item has a right child and the right child is not
// processed yet, then make sure right child is processed before node
if (node.right && st.peek() === node.right)
{
st.pop(st); // remove right child from stack
st.push(node); // push node back to stack
node = node.right; // change node so that the right
// child is processed next
}
else
{
callback(node);
node = null;
}
}
}