-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.js
More file actions
79 lines (70 loc) · 1.58 KB
/
binarySearchTree.js
File metadata and controls
79 lines (70 loc) · 1.58 KB
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
let {genDisorderList} = require("./tools")
var uuid = 0
function Node(value, left, right) {
this.value = value
this.id = (uuid++)
this.left = left || null
this.right = right || null
}
/***
* 构建二叉检索树
* @param array
* @constructor
*/
function BinarySearchTreeBuilder(array) {
if (this.root === undefined) {
this.root = new Node(array[0])
}
for (let i = 1; i < array.length; i++) {
this.compare(this.root, array[i])
}
this.print(this.root)
}
BinarySearchTreeBuilder.prototype.print = function(node) {
if (node.left) {
this.print(node.left)
}
console.log(node.value)
if (node.right) {
this.print(node.right)
}
}
BinarySearchTreeBuilder.prototype.compare = function(node, item) {
if (item > node.value) {
if (node.right) {
this.compare(node.right, item)
} else {
node.right = new Node(item)
}
} else {
if (node.left) {
this.compare(node.left, item)
} else {
node.left = new Node(item)
}
}
}
/***
* 用构建好的二叉检索树查找,快的不得了~
* @param node
* @param target
* @returns {*}
*/
function search(node, target) {
if (Math.abs(node.value - target) < 1) {
return node.id
}
if (node.value > target) {
return search(node.left, target)
} else {
return search(node.right, target)
}
}
let origin = genDisorderList(200)
let tree = new BinarySearchTreeBuilder(origin)
let target = origin[Math.ceil(Math.random() * origin.length) - 1]
console.log(`搜寻目标:${target}`)
let begTime = Date.now()
let result = search(tree.root, target)
console.log(`耗时:${Date.now() - begTime}`)
console.log(`目标ID:${result}`)