forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
48 lines (47 loc) · 1.11 KB
/
index.js
File metadata and controls
48 lines (47 loc) · 1.11 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
// --- Directions
// 1) Create a node class. The constructor
// should accept an argument that gets assigned
// to the data property and initialize an
// empty array for storing children. The node
// class should have methods 'add' and 'remove'.
// 2) Create a tree class. The tree constructor
// should initialize a 'root' property to null.
// 3) Implement 'traverseBF' and 'traverseDF'
// on the tree class. Each method should accept a
// function that gets called with each element in the tree
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
add(data) {
this.children.push(new Node(data));
}
remove(data) {
this.children = this.children.filter((node) => {
return node.data !== data;
});
}
}
class Tree {
constructor() {
this.root = null;
}
}
traverseBF(fn){
const arr=[this.root];
while(arr.length){
const node = arr.shift();
arr.push(...node.children);
fn(node);
}
}
traverseDF(fn){
const arr =[this.root];
while(arr.length){
const node=arr.shift();
arr.unshift(...node.children)
fn(node);
}
}
module.exports = { Tree, Node };