-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.js
67 lines (59 loc) · 1.51 KB
/
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
/*
Trees are data structures which are uni-directional
They cannot have loops of references.
Sample Tree Structure:
Tree {
root: {
value,
children: [
{
value,
children: [...]
},
{
value,
children: [...]
}
]
}
}
Functions for a Tree include "traverse" to loop through
the tree
add an element to the tree
*/
class Tree {
constructor() {
this.root = null;
}
// The traverse function will take a callback function
// as argument and loop over the tree from the root
// to its children
traverse(callback) {
function walk(node) {
// Call the callback function on the current node
callback(node);
// loop over the node's children recursively
node.children.forEach(walk);
}
// Start the traversal process
walk(this.root);
}
// lets add an element to one of the node's children
add(value, parentValue) {
let newNode = {
value,
children: []
};
// if there is no root, set it to the newNode
if (this.root === null) {
this.root = newNode;
return;
}
// Else traverse through the tree and find the node, and add it to it's children
this.traverse(node => {
if (node.value === parentValue) {
node.children.push(newNode);
}
});
}
}