-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathES5.html
88 lines (79 loc) · 2.3 KB
/
ES5.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Binary tree</title>
<script type="text/javascript">
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function Tree() {
this.root = null;
}
Tree.prototype.insert = function (value) {
var node = new Node(value);
var current = this.root;
if (!this.root) {
this.root = new Node(value);
return true;
}
while (current !== null) {
if (value < current.value) {
if (current.left === null) {
current.left = node;
break;
} else {
current = current.left;
}
} else {
if (current.right === null) {
current.right = node;
break;
} else {
current = current.right;
}
}
}
return true;
};
Tree.prototype.search = function (value) {
var current = this.root;
while (current !== null) {
console.log(current.value);
if (value === current.value) {
console.log('get!');
return true;
}
current = value > current.value ? current.right : current.left;
}
console.log('cannot find!');
return false;
};
Tree.prototype.preOrderTraverse = function (node) {
if (node) {
console.log(node.value);
this.preOrderTraverse(node.left);
this.preOrderTraverse(node.right);
}
};
// test code
var tree = new Tree();
tree.insert(7);
tree.insert(8);
tree.insert(10);
tree.insert(9);
tree.insert(3);
tree.insert(12);
tree.insert(11);
tree.insert(4);
tree.insert(5);
tree.insert(1);
tree.search(3);
tree.preOrderTraverse(tree.root);
</script>
</head>
<body>
</body>
</html>