Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solve garageScript#49, Lesson 2: bfsArr - Takes in a tree & returns a…
Browse files Browse the repository at this point in the history
…n array of each level
Alberto Lopez committed Oct 25, 2017
1 parent 5f41bae commit 8a9eebb
Showing 2 changed files with 39 additions and 26 deletions.
38 changes: 12 additions & 26 deletions solutions/bfsArr.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
const tree = {
val: 10,
children: [{val:1, children:[{val:3,children:[]},{val:4,children:[]}]},{val:2, children:[{val:5,children:[]},{val:6,children:[]}]}]
};

const bfs = (lev=[])=>{
if(!lev.length){
return;
}
n = lev.pop();
console.log(n);
return bfs(lev.concat(n.children));
const bfs = (current, next=[], result=[current.slice()])=>{
if(current.length === 0 && next.length === 0){
return result;
}
if(current.length === 0){
result.push(next.slice());
return bfs(next, [], result);
}else{
n = current.shift();
return bfs(current, next.concat(n.children), result);
}
}
console.log(bfs([tree]));

/*
const dfs = (lev=[])=>{
if(!lev.length){
return;
}
n = lev.pop();
console.log(n.getData());
dfs(lev.concat(n.children));
}
dfs([tree]);
*/
module.exports = bfs;
27 changes: 27 additions & 0 deletions test/bfsArr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const solution = require('../solutions/bfsArr.js');

const tree = {
val: 1,
children: [{val:2,children:[]},{val:3,children:[]}]
}

const tree2 = {
val: 1,
children: [{val:2,children:[{val:4,children:[]},{val:5,children:[]}]},{val:3,children:[{val:6,children:[]},{val:7,children:[]}]}]
}

const tree3 = {
val: 1,
children: [{val:2,children:[{val:4,children:[]},{val:5,children:[]}]},{val:3,children:[{val:6,children:[]},{val:7,children:[{val:9,children:[]}]}]}]
}

const test = (current, result)=>{
if(solution(current).length === result){
console.log('correct levels ');
}else{
console.log('incorrect levels ');
}
}
test([tree], 1);
test([tree2], 3);
test([tree3], 4);

0 comments on commit 8a9eebb

Please sign in to comment.