R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Breadth-First Print}
The Question
Breakdown
- Make a tree
- Figure out how to store the nodes
- Write function that walks though tree and stores the nodes
- Log the stored nodes to the console
1. Make a tree
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: []
}]
}]
};
2. Figure out how to store nodes
// 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
3. Write a function that walks through the tree and stores the nodes
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 );
}
4. Log the stored nodes to the console
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(' ') );
});
}
Conclusion
There are a few ways to do this problem ... this is just one solution ... go look them up on the GOOGLs
And also,
Reacto:Breadth-First Print
By Benjamin Conant
Reacto:Breadth-First Print
- 2,524