🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 深度遍历优先与广度遍历优先的区别 * 深度遍历优先,先找子孙后代,再找兄弟, 有回溯(入栈弹栈)操作,所以速度慢些 * 广度遍历优先,先找兄弟,再找子孙,无回溯速度快,但是多了队列的存储,占用内存会大些 <br> ## 深度遍历优先 ``` var tree = [{ name: '文件夹0', expand: false, children: [{ name: '文件夹2', expand: false, children: [{ name: '文件夹4', expand: false, }, { name: '文件夹5', expand: false, children: [{ name: '文件夹6', expand: false, children: [{ name: '文件夹7', expand: false, children: [{ name: '文件夹8', expand: false, children: [{ name: '文件夹9', expand: false, children: [{ name: '文件夹10', expand: false, children: [{ name: '文件夹11', expand: false, children: [{ name: '文件夹12', expand: false, children: [{ name: '文件夹13', expand: false, children: [{ name: '文件夹14', expand: false, children: [{ name: '文件夹15', expand: false }] }] }] }] }] }] }] }] }] }] }] }, { name: '文件夹3', expand: false } ] }, { name: '文件夹1', expand: false } ] // 深度遍历优先 function expandAll(tree) { tree.forEach(node => { node.expand = true; if (node.children && Array.isArray(node.children) && node.children.length > 0) { expandAll(node.children); } }); } // 开始计算t1时间 console.time('t1'); for (let i = 0; i < 10000; i++) { expandAll(tree); } // t1时间计算结束 console.timeEnd('t1'); console.log(tree); ``` <br> ## 广度优先遍历 ``` var tree = [{ name: '文件夹0', expand: false, children: [{ name: '文件夹2', expand: false, children: [{ name: '文件夹4', expand: false, }, { name: '文件夹5', expand: false, children: [{ name: '文件夹6', expand: false, children: [{ name: '文件夹7', expand: false, children: [{ name: '文件夹8', expand: false, children: [{ name: '文件夹9', expand: false, children: [{ name: '文件夹10', expand: false, children: [{ name: '文件夹11', expand: false, children: [{ name: '文件夹12', expand: false, children: [{ name: '文件夹13', expand: false, children: [{ name: '文件夹14', expand: false, children: [{ name: '文件夹15', expand: false }] }] }] }] }] }] }] }] }] }] }] }, { name: '文件夹3', expand: false } ] }, { name: '文件夹1', expand: false } ] // 广度遍历优先 function expandAll(tree) { let queue = []; tree.forEach(node => { queue.push(node); }); for(;queue.length > 0;){ let node = queue.shift(); node.expand = true; if(Array.isArray(node.children) && node.children.length > 0){ node.children.forEach(child => { queue.push(child); }); } } } console.time('t2'); for (let i = 0; i < 10000; i++) { expandAll(tree); } console.timeEnd('t2'); console.log(tree); ```