-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
105 lines (81 loc) · 2.67 KB
/
index.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { BinaryTreeNode, drawBinaryTree, VisualizationType } from 'binary-tree-visualizer';
// variable for printing purpose
let InOrders = "";
let PreOrders = "";
let PostOrders = "";
function start(){
// getting array as string from the text box
var txt = document.getElementById('txt').value;
// sanitizing the string and creating an array
var txtArr = txt.split(",").map(function(item) {
return item.trim();
});
// if first element of array is empty string just clear all the placeholders
// including the canvas
if (txtArr[0] === '') {
document.getElementById("preOrder").innerHTML = "";
document.getElementById("inOrder").innerHTML = "";
document.getElementById("postOrder").innerHTML = "";
let canvas_elem = document.querySelector('canvas');
canvas_elem.getContext('2d').clearRect(0, 0, canvas_elem.width, canvas_elem.height);
return;
}
// creating the binary tree
let root = createTree(txtArr);
// drawing the binary tree by using the package from here
drawBinaryTree(root, document.querySelector('canvas'), {
type: VisualizationType.SIMPLE
});
PreOrders = "";
printPreorder(root);
document.getElementById("preOrder").innerHTML = "<b>Pre-order:</b> " + PreOrders.trim();
InOrders = "";
printInorder(root);
document.getElementById("inOrder").innerHTML = "<b>In-order:</b> " + InOrders.trim();
PostOrders = "";
printPostorder(root);
document.getElementById("postOrder").innerHTML = "<b>Post-order:</b> " + PostOrders.trim();
}
// this is responsible for drawing the whole tree in the canvas
function createTree(arr){
let nodes = [];
arr.forEach((elem) => {
if (elem.toLowerCase() === 'null' || elem.toLowerCase() === 'none')
nodes.push(null);
else
nodes.push(new BinaryTreeNode(elem));
});
let kids = nodes.slice().reverse();
let root = kids.pop();
nodes.forEach((node) => {
if(node) {
if (kids)
node.left = kids.pop();
if (kids)
node.right = kids.pop();
}
});
return root;
}
function printInorder(node) {
if (node == null)
return;
printInorder(node.left);
InOrders += node.value + " ";
printInorder(node.right);
}
function printPreorder(node) {
if (node == null)
return;
PreOrders += node.value + " ";
printPreorder(node.left);
printPreorder(node.right);
}
function printPostorder(node) {
if (node == null)
return;
printPostorder(node.left);
printPostorder(node.right);
PostOrders += node.value + " ";
}
window.start = start;