๐ Breadth First Search(BFS)
Question Descriptionโ
ๅปฃๅบฆๅชๅ ๆๅฐๆผ็ฎๆณ
่ซๅ่ฉฆไฝฟ็จๅปฃๅบฆๅชๅ ๆๅฐๆณไพ้ๆญท่ฑๆ ผ่ญไธๅๆไปฃ็ๅ้ฎ
const heptarchyTree = {
value: 'England', // ่ฑๆ ผ่ญ
children: [
{
value: 'Northumbria', // ่ซพๆฃฎๅธ้ไบ็ๅ
children: [
{
value: 'Bamburgh', // ็ญๅธๅๅ
children: [
{
value: 'Yeavering', // ่ถ็ฆๆ่ๅ
children: [],
},
],
},
{
value: 'Lindisfarne', // ๆ่ฟชๆฏๆณๆฉ
children: [],
},
],
},
{
value: 'Mercia', // ้บฅ่ฅฟไบ็ๅ
children: [
{
value: 'Tamworth', // ๅกๅงๆฒๆฏ
children: [],
},
{
value: 'Repton', // ้ทๆฎ้
children: [],
},
],
},
],
};
function travelThroughHeptarchy(heptarchyTree) {
const scroll = []; // ไฝฟ็จ็พ็ฎ็ด็ด้่จชๅๅๅฐ็้ ๅบ
scroll.push(heptarchyTree); // ๅฐ่ฑๆ ผ่ญไฝ็บ่ตท้ปๅ ๅ
ฅ็พ็ฎ็ด
// ็ถ็พ็ฎ็ดไธ้ๆๅ้ฎๆ๏ผ็นผ็บ้ๆญท
while (scroll.length > 0) {
const kingdom = scroll.shift(); // ๅพ็พ็ฎ็ดไธๅไธไธๅ่ฆ่จชๅ็็ๅๆๅ้ฎ
console.log(kingdom.value); // ่จ้่จชๅ็็ๅๆๅ้ฎๅ็จฑ
// ้ๆญท็ถๅ็ๅๆๅ้ฎ็ๆๆๅญๅๅ๏ผไธฆๅฐๅฎๅๅ ๅ
ฅ็พ็ฎ็ด
for (const child of kingdom.children) {
scroll.push(child);
}
}
}
travelThroughHeptarchy(heptarchyTree); // ้ๅง้ๆญท่ฑๆ ผ่ญไธๅๆไปฃ็ๅ้ฎ