-
Notifications
You must be signed in to change notification settings - Fork 21
/
binary-tree.js
93 lines (79 loc) · 1.67 KB
/
binary-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
function BinaryTree() {
this._root = null;
this.left = null;
this.right = null;
this.size = 0;
}
BinaryTree.prototype.addChild = function(value) {
var node = {
value: value,
left: null,
right: null
}
this.size += 1;
if (!this._root) {
this.root = node;
} else{
var current = this._root;
while (true) {
if (value < current.value) {
if (current.left === null) {
current.left = node;
break;
} else {
current = current.left;
}
} else if (value > current.value) {
if (current.right === null) {
current.right = node;
break;
} else {
current = current.right;
}
} else {
break;
}
}
}
}
BinaryTree.prototype.contains = function(value) {
var current = this._root;
var found = false;
while (!found && current) {
if (value < current.value) {
current = current.left;
} else if(value > current.value) {
current = current.right;
} else {
found = true;
}
return found;
}
}
BinaryTree.prototype.traverse = function(process) {
function inOrder(node) {
if (node) {
if (node.left !== null) {
inOrder(node.left);
}
process.call(this, node);
if (node.right !== null) {
inOrder(node.right);
}
}
}
inOrder(this._root);
}
BinaryTree.prototype.toArray = function() {
var result = [];
this.traverse(function (node) {
result.push(node.value);
});
return result;
}
BinaryTree.prototype.toString = function() {
return this.toArray().toString();
}
BinaryTree.prototype.getSize = function() {
return this.size;
}