<!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 (tree) { tree.forEach(item => { console.log(item) if (item.children) { arguments.callee(item.children) } }) })(tree); console.log('广度遍历'); (function (tree) { let child = [] tree.forEach(item => { console.log(item); if (item.children) { child = child.concat(item.children) } }) if (child.length) { arguments.callee(child) } })(tree);