-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinarySearchTree.html
56 lines (48 loc) · 1.55 KB
/
binarySearchTree.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>binarySearchTree</title>
</head>
<body>
<script type="text/javascript">
function BinarySearchTree() {
this.Node = function (key) {
this.key = key;
this.left = null;
this.right = null;
}
this.root = null;
this.insertNode = function (node, newNode) {
if (newNode.key < node.key) {
if (node.left === null) {
node.left = newNode
} else {
this.insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
}
}
BinarySearchTree.prototype.insert = function (key) {
let newNode = new this.Node(key);
if (this.root === null) {
this.root = newNode
} else {
this.insertNode(this.root, newNode);
}
}
let nodes = [8, 3, 10, 1, 6, 14, 4, 7, 13];
let tree1 = new BinarySearchTree();
nodes.forEach(key => tree1.insert(key));
console.log(tree1.root);
</script>
</body>
</html>