This repository was archived by the owner on Jun 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 354
Expand file tree
/
Copy pathdius00_dataStructure_Tree.js
More file actions
89 lines (83 loc) · 2.67 KB
/
dius00_dataStructure_Tree.js
File metadata and controls
89 lines (83 loc) · 2.67 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
80
81
82
83
84
85
86
87
88
89
// Javascript ES6 syntax code sample for Tree (non-binary) data structure
/*
* Creates the Tree
* if a value is given to the constructor
* the element will be initialized as an instance of Tree
*/
class Tree {
constructor(value) {
if(value !== undefined){
this.value = value;
this.children = [];
}
}
/*
* Method to add a new child to the Tree
*/
addChild(value) {
const newTree = new Tree(value); // Generates a new Tree element
this.children.push(newTree); // Adds the newTree (child) to the children Array
return newTree; // Returns the new Tree
}
/*
* Method to check if a value exists in the tree
*/
contains(value) {
// initializes the result as false
let result = false;
/*
* declare a searchValue function that travels recursivly
* through the Tree and his Childre
*/
function searchValue(tree) {
// if the current Tree value is equal to the one we are looking for
// change the result to true
if (tree.value === value) result = true;
// if the Tree has children
if (tree.children !== []) {
// for each of them call an instance of the searchValue function
for (const child of tree.children) searchValue(child);
}
}
// call the searchValue function on or parent Tree
searchValue(this);
// returns the result
return result;
}
/*
* Method to remove and
* return all the (children) Trees if it they a certain value
*/
remove(value) {
// initializes the array that will contain all the removed trees
const removedTrees = [];
/*
* declare a removeValue function that travels recursivly
* through the Tree and his Children, if it finds a child
* with the matching value, it pushed it to removedTrees
* and removes it from the list of children
*/
function removeValue(tree) {
// if a tree has children
if (tree.children !== []) {
// iterate through the children
for (const child of tree.children) {
// if the child(Tree) has a matching value
if (child.value === value) {
// pushes the child(Tree) into removedTrees
removedTrees.push(child);
// removes the child(Tree) from the parent children array
tree.children.splice(tree.children.indexOf(removedValue), 1);
}
}
// afterwards iterates through the remaining children
// by calling removeValue recursivly
for (const child of tree.children) removeValue(child);
}
}
// calls removeValue
removeValue(this);
// returns the removed value
return removedValue;
}
}