public
Created

  • Download Gist
bfs.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
var o = {
value: 1,
left: {
value: 2,
left: {
value: 4
},
right: {
value: 5
}
},
right: {
value: 3,
left: {
value: 6
},
right: {
value: 7
}
}
};
 
var fn = function (node) {
var arr = [];
 
var l = node.left;
var r = node.right;
 
l && arr.push(l.value);
r && arr.push(r.value);
 
if (l) {
arr = arr.concat(fn(l));
}
 
if (r) {
arr = arr.concat(fn(r));
}
 
if (arr.length === 6) {
arr.unshift(node.value);
}
 
return arr;
};
 
console.log(fn(o));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.