<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<title>树 深度、广度遍历</title>
</head>
<body>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-size: 16px;
color: #adbac7;
background-color: #22272e;
}
let tree = [
{
no: 1,
children: [
{
no: 2
},
{
no: 3
}
]
},
{
no: 4,
children: [
{
no: 5
},
{
no: 6,
children: [
{
no: 7
},
{
no: 8
}
]
}
]
},
{
no: 9
}
];
console.log('树 深度、广度遍历');
console.log(JSON.stringify(tree, null, 2));
console.log('深度遍历');
(function fn1(tree) {
tree.forEach(item => {
console.log(item)
if (item.children) {
fn1(item.children)
}
})
})(tree);
console.log('广度遍历');
console.time();
(function fn2(tree) {
let child = []
tree.forEach(item => {
console.log(item);
if (item.children) {
child = child.concat(item.children)
}
})
if (child.length) {
fn2(child)
}
})(tree);
console.timeEnd();
console.log('广度遍历 2');
console.time();
(function (tree) {
let queue = [...tree];
while (queue.length > 0) {
let item = queue.shift();
console.log(item);
if (item.children) {
queue.push(...item.children);
}
}
})(tree);
console.timeEnd();