-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeJavaScript.js
86 lines (73 loc) · 2.43 KB
/
BinaryTreeJavaScript.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
// Creating a Binary Tree in JavaScript
class BinaryTreeNode {
// Classes in JavaScript require constructor and this. notation to set class properties.
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
var traverseCount = 0;
// Left - Root - Right
function inOrderTraverse(node) {
if(node != null)
{
traverseCount++;
inOrderTraverse(node.left);
console.log(node);
inOrderTraverse(node.right);
console.log(traverseCount);
}
}
// Root - Left - Right
function preOrderTraverse(node) {
while (node != null) {
console.log(node);
preOrderTraverse(node.left);
preOrderTraverse(node.right);
}
}
// Left - Right - Root
function postOrderTraverse(node) {
while (node != null) {
postOrderTraverse(node.left);
postOrderTraverse(node.right);
console.log(node);
}
}
const arrayOfTreeData = [12, 18, 13, 1, 3, 20, 17, 19];
const binaryTreeRoot = new BinaryTreeNode(arrayOfTreeData[0]);
for(var i = 1; i < arrayOfTreeData.length; i++) {
var current = new BinaryTreeNode(arrayOfTreeData[i]);
var previous = binaryTreeRoot;
console.log(`Inserting ${arrayOfTreeData[i]}`);
var insertedNode = false;
while(!insertedNode) {
if(current?.value < previous?.value) {
if(previous.left == null) {
console.log("Left Node is null, adding", current);
// No node on left, set new node
previous.left = current;
}
else {
// Node already on left, so travers downward to the left further
console.log("Node already on the right of", previous.value);
previous = previous.left;
}
}
else if(current?.value > previous?.value) {
if(previous.right == null) {
// No node on right, set new node
console.log("Right node is null, adding", current);
previous.right = current;
}
else {
// Node already on right, so traverse downward to the right further
console.log("Node already on the right of", previous.value);
previous = previous.right;
}
}
insertedNode = true;
}
}
inOrderTraverse(binaryTreeRoot);