求助:如何用JavaScript从字符串数组生成指定结构的随机树?
按层填充的3叉树生成实现
需要将给定的字符串数组生成一棵3叉树,要求先填满当前层级所有父节点的子节点,再进入下一层级,每个父节点最多3个子节点。以下是简洁高效的非递归实现:
function buildLevelOrderTree(arr, maxChildren = 3) { if (!arr.length) return []; const tree = []; const queue = []; let index = 0; // 构建第一层根节点 const rootCount = Math.min(maxChildren, arr.length); for (let i = 0; i < rootCount; i++) { const node = { parent: arr[index++], children: [] }; tree.push(node); queue.push(node); } // 广度优先填充后续层级 while (queue.length && index < arr.length) { const currentNode = queue.shift(); // 给当前节点添加最多3个子节点,直到数组耗尽 while (currentNode.children.length < maxChildren && index < arr.length) { const childNode = { parent: arr[index++], children: [] }; currentNode.children.push(childNode); queue.push(childNode); } } return tree; } // 测试示例数组 const x = [ 'apple', 'bus', 'banana', 'pen', 'pencil', 'earth', 'planet', 'flat', 'house', 'dream', 'train', 'space', 'drink', 'cola' ]; // 输出与预期一致的树结构 console.log(JSON.stringify(buildLevelOrderTree(x), null, 2));
核心逻辑说明
- 广度优先遍历(BFS):严格遵循“先填满当前层级所有节点,再进入下一层”的要求,避免递归带来的冗余代码
- 队列管理:用队列跟踪待填充子节点的节点,确保处理顺序完全符合层级填充规则
- 自适应边界处理:自动适配数组长度不足的情况,无需额外判断,避免数组越界错误
- 可配置子节点数:通过
maxChildren参数可以轻松修改每个父节点的最大子节点数,默认值为3
运行上述代码后,生成的树结构与你提供的预期结果完全匹配。
内容的提问来源于stack exchange,提问作者krots
相关产品推荐
相关产品推荐

