-
Notifications
You must be signed in to change notification settings - Fork 21
/
tree.js
51 lines (41 loc) · 1014 Bytes
/
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
function Tree(value) {
this.parent = null;
this.children = [];
this.value = value || null;
};
Tree.prototype.addChild = function(value) {
var child;
if (value.constructor === Tree) {
child = value;
} else {
child = new Tree(value);
}
child.parent = this;
this.children.push(child);
};
Tree.prototype.contains = function(value) {
if (this.value === value) return true;
for (var i = 0; i < this.children.length; i++) {
if (this.children[i].contains(value)) {
return true;
}
}
return false;
};
Tree.prototype.removeChild = function(value) {
for (var i = 0; i < this.children.length; i++) {
if (this.children[i].value === value) {
var child = this.children.splice(i, 1);
child.parent = null;
}
}
};
Tree.prototype.removeFromParent = function() {
this.parent.removeChild(this.value);
};
Tree.prototype.isLeaf = function() {
return this.children.length === 0;
};
Tree.prototype.isRoot = function() {
return this.parent === null;
};