ES6 递归函数生成树形结构 - 详解与示例
使用递归函数可以轻松生成树形结构。以下示例代码展示了如何使用 ES6 递归函数生成一个深度为 3 的树形结构,并输出 '0.children.0.children.0' 节点。
function generateTree(depth) {
if (depth === 0) {
return null;
}
const node = {
'children': []
};
node['children'].push(generateTree(depth - 1));
return node;
}
const tree = generateTree(3);
console.log(tree['children'][0]['children'][0]);
这段代码通过递归函数 generateTree,根据传入的深度参数 depth 生成相应的树形结构。
- 当
depth为 0 时,返回null,表示树的末端。 - 否则,创建一个节点
node,并递归调用generateTree生成子节点,并将子节点添加到node的'children'属性中。
最后,通过 console.log(tree['children'][0]['children'][0]) 输出 '0.children.0.children.0' 节点。
您可以通过调整 depth 参数来生成不同深度的树形结构。例如,将 depth 设置为 5,则会生成一个深度为 5 的树形结构。
原文地址: https://www.cveoy.top/t/topic/oPfg 著作权归作者所有。请勿转载和采集!