1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| interface TreeNode { code?: string; value?: string; children?: TreeNode[]; [key: string]: any; }
function transformTreeDFS(tree: TreeNode[]): TreeNode[] { const stack: TreeNode[] = [...tree]; while (stack.length) { const node = stack.pop()!; if (node.code !== undefined) { node.value = node.code; delete node.code; } if (node.children?.length) { // 从右向左压入栈,这样出栈时就是从左向右处理 // 也可以这么做 stack.push(...node.children.reverse()); for (let i = node.children.length - 1; i >= 0; i--) { stack.push(node.children[i]); } } } return tree; }
|