Skip to content

Commit 1b83294

Browse files
committed
Added preorder binary tree traversal
1 parent 9ec605a commit 1b83294

File tree

4 files changed

+59
-1
lines changed

4 files changed

+59
-1
lines changed

algorithm/tree/binary_tree_traversal/desc.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"<a href='https://en.wikipedia.org/wiki/Tree_traversal'>Wikipedia</a>"
1616
],
1717
"files": {
18-
"inorder": "Traverse Binary Tree Inorder"
18+
"inorder": "Traverse Binary Tree Inorder",
19+
"preorder": "Traverse Binary Tree Preorder"
1920
}
2021
}

algorithm/tree/binary_tree_traversal/inorder/code.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ function inorder ( root , parent ) {
2121
}
2222

2323
inorder ( 5 ); // node with key 5 is the root
24+
logger._print( 'Finished' );
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var index = 0;
2+
3+
function inorder ( root , parent ) {
4+
if (root === -1) {
5+
logger._print( 'No more nodes. Backtracking.' )._wait ();
6+
return;
7+
}
8+
9+
logger._print( 'Reached ' + root);
10+
treeTracer._visit ( root , parent )._wait ();
11+
12+
logger._print( 'Printing ' + root);
13+
treeTracer._leave ( root );
14+
arrayTracer._notify ( index++, root )._wait();
15+
16+
logger._print ( ' Going left from ' + root )._wait ();
17+
inorder(T[root][0], root);
18+
19+
logger._print ( ' Going right from ' + root )._wait ();
20+
inorder(T[root][1], root);
21+
}
22+
23+
inorder ( 5 ); // node with key 5 is the root
24+
logger._print( 'Finished' );
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
var G = [ // G[i][j] indicates whether the path from the i-th node to the j-th node exists or not
2+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
3+
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
4+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
5+
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0],
6+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
7+
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
8+
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
9+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
10+
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
11+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
12+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
13+
];
14+
15+
16+
var T = [ // mapping to G as a binary tree , [i][0] indicates left child, [i][1] indicates right child
17+
[-1,-1],
18+
[ 0, 2],
19+
[-1,-1],
20+
[ 1, 4],
21+
[-1,-1],
22+
[ 3, 8],
23+
[-1, 7],
24+
[-1,-1],
25+
[ 6,10],
26+
[-1,-1],
27+
[ 9,-1]
28+
];
29+
30+
var treeTracer = new DirectedGraphTracer( " Binary Tree Traversal Inorder ")._setTreeData ( G, 5 );
31+
var arrayTracer = new Array1DTracer( " Binary Tree Print Inorder ")._setData ( new Array(T.length).fill( '-' ) );
32+
var logger = new LogTracer ( " Log ");

0 commit comments

Comments
 (0)