先将树的第一层全部放入栈中,然后做出栈操作,操作数据,如果有children继续将children放入栈中,通过重复的该过程实现直至空栈来实现递归
interface Node {
name: string
id: string
children: Array<Node>
[key: string]: any
}
class Stack<T> {
private _stack: T[]
constructor(maxSize?: number) {
this._stack = new Array(maxSize || 0)
}
public isEmpty(): boolean {
return this._stack.length === 0
}
public size(): number {
return this._stack.length
}
public top(): T {
return this._stack[length - 1]
}
public push(...items: T[]): number {
if (items) {
this._stack.push(...items)
}
return this.size()
}
public pop(): T | string {
if (!this.isEmpty()) {
return this._stack.pop() || '空栈'
}
return '空栈'
}
}
export const traverse = (tree: Array<Node>): Array<Node> | string => {
const { length } = tree || []
if (!length) return '空树'
const stack = new Stack<Node>()
const result = JSON.parse(JSON.stringify(tree || []))
stack.push(...result)
do {
const topData = stack.pop()
if (typeof topData === 'string') return '空栈'
Object.defineProperty(topData, 'traverse', { value: true })
const { children } = topData || {}
const { length } = children || []
if (length) {
stack.push(...children)
}
} while (!stack.isEmpty())
return result
}