遍历树形结构的菜单,实现子菜单的添加与删除。
菜单的树形结构:node
要实现的功能:编程
这两种功能都须要遍历多叉树。
这就涉及到你们不肯去触碰的多叉树遍历了....刚开始是循环套循环套循环....看得本身都昏了。
后来鼓起勇气从新来过。函数
递归遍历多叉树spa
百度百科对递归的定义是:程序调用自身的编程技巧称为递归( recursion)。
而我对递归的理解就是把大问题切分红一个一个小问题。也就是不断缩小参数范围。
我在写递归函数的时候是分了三步。code
具体代码递归
export const addMenu = (node, fatherKey, newDirectoryTitle) => { if (!node) { return; } if(node.key === fatherKey) { const child = { type: `${node.key}-${node.childType}`, title: newDirectoryTitle, key: `${node.key}-${node.childType}`, childType: 0, children:[], } node.childType += 1; node.children.push(child); return; } if(node.children && node.children.length > 0) { for(let i =0 ;i < node.children.length; i++) { addMenu(node.children[i],fatherKey,newDirectoryTitle); } } };
删除子菜单的方法其实也是差很少。只是其中的处理逻辑不同。
回头再看看以前写的多叉树遍历,其实并不难,只是本身原来对它有了惯性的抗拒。get