File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ const Queue = require ( '../stacks-and-queues/queue' ) ;
2+ const LinkedList = require ( '../linked-list/linkedlist' ) ;
3+
4+ function listOfDepths ( root ) {
5+ const queue = new Queue ( ) ;
6+ const list = [ ] ;
7+ let depth = 0 ;
8+
9+ if ( ! root ) return list ;
10+
11+ queue . add ( root ) ;
12+ queue . add ( '*' ) ;
13+
14+ while ( ! queue . isEmpty ( ) ) {
15+ if ( queue . peek ( ) === '*' ) {
16+ queue . remove ( ) ;
17+ depth ++ ;
18+
19+ if ( queue . isEmpty ( ) ) {
20+ continue ;
21+ } else {
22+ queue . add ( '*' ) ;
23+ }
24+ }
25+
26+ const node = queue . remove ( ) ;
27+ add ( list , depth , node . data ) ;
28+
29+ node . adjacents . forEach ( function ( adj ) {
30+ queue . add ( adj ) ;
31+ } ) ;
32+ }
33+
34+ return list ;
35+ }
36+
37+ function add ( list , depth , data ) {
38+ list [ depth ] = list [ depth ] || new LinkedList ( ) ;
39+ list [ depth ] . addLast ( data ) ;
40+ }
41+
42+ module . exports = listOfDepths ;
Original file line number Diff line number Diff line change 1+ const expect = require ( 'chai' ) . expect ;
2+ const Node = require ( './graph' ) . Node ;
3+ const listOfDepths = require ( './list-of-depths' ) ;
4+
5+ describe ( 'Graph: List of depths' , function ( ) {
6+
7+ it ( 'should work with 0 elements' , function ( ) {
8+ let list = listOfDepths ( ) ;
9+ expect ( list . length ) . to . equal ( 0 ) ;
10+ } ) ;
11+
12+
13+ it ( 'should work with 1 element' , function ( ) {
14+ let tree = new Node ( 'a' ) ;
15+ let list = listOfDepths ( tree ) ;
16+ expect ( list . length ) . to . equal ( 1 ) ;
17+ expect ( list [ 0 ] . toString ( ) ) . to . equal ( 'a' ) ;
18+ } ) ;
19+
20+ it ( 'should work with tree depth 2' , function ( ) {
21+ let tree = new Node ( 'a' ) ;
22+ tree . adjacents = [ new Node ( 'b' ) , new Node ( 'c' ) ] ;
23+
24+ let list = listOfDepths ( tree ) ;
25+ expect ( list . length ) . to . equal ( 2 ) ;
26+ expect ( list [ 1 ] . toString ( ) ) . to . equal ( 'b -> c' ) ;
27+ } ) ;
28+
29+ it ( 'should work with tree depth 3' , function ( ) {
30+ let a = new Node ( 'a' ) ,
31+ b = new Node ( 'b' ) ,
32+ c = new Node ( 'c' ) ,
33+ d = new Node ( 'd' ) ,
34+ e = new Node ( 'e' ) ,
35+ f = new Node ( 'f' ) ,
36+ g = new Node ( 'g' ) ;
37+
38+ b . adjacents = [ d , e ] ;
39+ c . adjacents = [ f , g ] ;
40+ a . adjacents = [ b , c ] ;
41+
42+ let list = listOfDepths ( a ) ;
43+ expect ( list . length ) . to . equal ( 3 ) ;
44+ expect ( list [ 2 ] . toString ( ) ) . to . equal ( 'd -> e -> f -> g' ) ;
45+ } ) ;
46+ } ) ;
You can’t perform that action at this time.
0 commit comments