From 8a9eebbecbd54820d5ca728ed23ac661b1f57880 Mon Sep 17 00:00:00 2001 From: Alberto Lopez Date: Wed, 25 Oct 2017 11:59:08 -0700 Subject: [PATCH] Solve #49, Lesson 2: bfsArr - Takes in a tree & returns an array of each level --- solutions/bfsArr.js | 38 ++++++++++++-------------------------- test/bfsArr.js | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 26 deletions(-) create mode 100644 test/bfsArr.js diff --git a/solutions/bfsArr.js b/solutions/bfsArr.js index 894897f..7c28c49 100644 --- a/solutions/bfsArr.js +++ b/solutions/bfsArr.js @@ -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; diff --git a/test/bfsArr.js b/test/bfsArr.js new file mode 100644 index 0000000..2f7d7d9 --- /dev/null +++ b/test/bfsArr.js @@ -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);