forked from garageScript/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
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…
…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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |