-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbinary_search_tree.js
105 lines (95 loc) · 2.19 KB
/
binary_search_tree.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
105
function Node(data, left, right) {
this.data = data;
this.left = left;
this.right = right;
this.show = show;
this.remove = remove;
}
function BST() {
this.root = null;
this.insert = insert;
this.inOrder = inOrder;
this.preOrder = preOrder;
this.postOrder = postOrder;
}
function show() {
return this.data;
}
function insert(data) {
var n = new Node(data, null, null);
if(this.root === null) {
this.root = n;
} else {
var current = this.root, parent;
while(true) {
parent = current;
if(data < current.data) {
current = current.left;
if(current === null) {
parent.left = n;
break;
}
} else {
current = current.right;
if(current === null) {
parent.right = n;
break;
}
}
}
}
}
function remove(data) {
this.root = removeNode(this.root, data);
}
function removeNode(node, data) {
if(node === null) {
return null;
}
if(data === node.data) {
if (node.left === null && node.right === null) {
return null;
}
if (node.left === null) {
return node.right;
}
if (node.right === null) {
return node.left;
}
} else if(data === node.data) {
node.left = removeNode(node.left, data);
return node;
} else {
node.right = removeNode(node.right, data);
return node;
}
}
function inOrder(node) {
if(!(node === null)) {}
inOrder(node.left);
console.log(node.show() + '');
inOrder(node.right);
}
function preOrder(node) {
if (!(node === null)) {
console.log(node.show() + " ");
preOrder(node.left);
preOrder(node.right);
}
}
function postOrder(node) {
if (!(node === null)) {
postOrder(node.left);
postOrder(node.right);
console.log(node.show() + " ");
}
}
var nums = new BST();
nums.insert(23);
nums.insert(45);
nums.insert(16);
nums.insert(37);
nums.insert(3);
nums.insert(99);
nums.insert(22);
console.log(nums);