forked from OperationCode/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreOrderIterative.js
More file actions
46 lines (27 loc) · 838 Bytes
/
PreOrderIterative.js
File metadata and controls
46 lines (27 loc) · 838 Bytes
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
f
import BinaryTreeNode from './BinaryTreeNode';
import Stack from './../stack/Stack';
export function preOrderIterative(tree,callback){
var node = tree.store;
var st = new Stack();
if (!node)
return;
st.push(node);
/* Pop all items one by one. Do following for every popped item
a) callback
b) push its right child
c) push its left child
Note that right child is pushed first so that left is processed first */
while (!st.isEmpty() )
{
// Pop the top item from stack
node = st.pop();
// callback
callback(node);
// Push right and left children of the popped node to stack
if (node.right)
st.push(node.right);
if (node.left)
st.push(node.left);
}
}