3
3
4
4
2. Create a tree class. The tree constuctor should initialize a 'root' property to null.
5
5
6
- 3. Implement 'traverseBFS' and 'traverseDFS' on the trees class.
6
+ 3. Implement 'traverseBFS' and 'traverseDFS' on the trees class. Each method should accept a function that gets called with each element in the tree.
7
7
*/
8
8
9
9
class Node {
@@ -13,8 +13,13 @@ class Node {
13
13
}
14
14
15
15
// Add a new node to the children of current node.
16
- add ( data ) {
17
- this . children . push ( new Node ( data ) ) ;
16
+ add ( data , children = [ ] ) {
17
+ const newNode = new Node ( data ) ;
18
+ children . forEach ( elm => {
19
+ newNode . children . push ( new Node ( elm ) ) ;
20
+ } ) ;
21
+
22
+ this . children . push ( newNode ) ;
18
23
}
19
24
20
25
// Remove a data from the children of current node.
@@ -28,7 +33,53 @@ class Node {
28
33
} ;
29
34
30
35
class Tree {
31
- constructor ( ) {
32
- this . root = null ;
36
+ constructor ( root ) {
37
+ this . root = root || null ;
38
+ }
39
+
40
+ // Breadth first search (horizontal search)
41
+ traverseBFS ( callback ) {
42
+ const arr = [ this . root ] ;
43
+
44
+ while ( arr . length ) {
45
+ const node = arr . shift ( ) ;
46
+
47
+ // The key difference - Adding childrens to the end of array.
48
+ arr . push ( ...node . children ) ;
49
+ callback ( node ) ;
50
+ }
51
+ }
52
+
53
+ // Depth first search (vertical serach)
54
+ traverseDFS ( callback ) {
55
+ // this.root.children.forEach(node => {
56
+ // callback(node);
57
+
58
+ // const newTree = new Tree(node);
59
+
60
+ // newTree.traverseDFS(callback);
61
+ // });
62
+
63
+ const arr = [ this . root ] ;
64
+
65
+ while ( arr . length ) {
66
+ const node = arr . shift ( ) ;
67
+
68
+ // The key difference - Adding childrens to the start of array.
69
+ arr . unshift ( ...node . children ) ;
70
+ callback ( node ) ;
71
+ }
33
72
}
34
- } ;
73
+ } ;
74
+
75
+ const node = new Node ( 20 ) ;
76
+
77
+ node . add ( 0 , [ 12 , - 2 , 1 ] ) ;
78
+ node . add ( 40 ) ;
79
+ node . add ( - 15 , [ - 2 ] ) ;
80
+
81
+ const tree = new Tree ( node ) ;
82
+
83
+ tree . traverseBFS ( ( node ) => console . log ( node . data ) ) ;
84
+ console . log ( "-------------" ) ;
85
+ tree . traverseDFS ( ( node ) => console . log ( node . data ) ) ;
0 commit comments