xamples
epeat
ode
pproach
ptimize
est
var myTree = {
value: 'A',
children: [{
value: 'B',
children: [{
value: 'D',
children: [{
value: 'H',
children: []
}]
}]
}, {
value: 'C',
children: [{
value: 'E',
children: []
}, {
value: 'F',
children: [{
value: 'I',
children: []
}, {
value: 'J',
children: []
}]
}, {
value: 'G',
children: []
}]
}]
};
// We want to use a hash ... basically an array of arrays
// for example
// var myHash = [["hello", "I am here"], ["yes hello", "I am in the hash to"],["me too"],[42]];
// the first element of the hash is said to be the lowest level
// the last element is said to be the highest level
// we will store each level of the tree as a level in the hash
// and then print the hash when we are done!
// we want to make this
var hash = [[firstNode], [secondNode, thirdNode], [forthNode, fifthNode, sixNode, seventhNode]]
//from this
1 // level 1
2 3 // level 2
4 5 6 7 7 // level 3
function printTreeLevels (startingNode) {
var levels = [];
(function collectVals (node, level) {
// if there is no level this deep yet, make it
levels[ level ] = levels[ level ] || [];
levels[ level ].push( node.value );
// recursively handle each child node, one level deeper
node.children.forEach(function (childNode) {
collectVals( childNode, level+1 );
});
})( startingNode, 0 );
}
function printTreeLevels (startingNode) {
var levels = [];
(function collectVals (node, level) {
// if there is no level this deep yet, make it
levels[ level ] = levels[ level ] || [];
levels[ level ].push( node.value );
// recursively handle each child node, one level deeper
node.children.forEach(function (childNode) {
collectVals( childNode, level+1 );
});
})( startingNode, 0 );
// Print the results
levels.forEach(function (level) {
console.log( level.join(' ') );
});
}
There are a few ways to do this problem ... this is just one solution ... go look them up on the GOOGLs
And also,