1、深度遍历
深度遍历利用栈来实现
class Stack { constructor () { this.top = 0, // 栈的长度 this.list = [] } push(item) { this.top++; this.list.push(item) // 入栈操作 } pop () { --this.top; return this.list.pop() // 出栈操作 } peek () { return this.list[this.top -1] // 查询栈顶元素 } } let treeData = { id: 0, name: '00', children: [ { id: 1, name: '01', children: [ { id: 11, name: '11', children: [] }] }, { id: 2, name: '02', children: [ { id: 22, name: '22', children: [] }] }] } function formatTreeData(data) { let stack = new Stack() stack.push(data); while(stack.top) { let item = stack.pop() for (let i in item.children) { stack.push(item.children[i]) } console.log(item.id) } } formatTreeData(treeData)
2、广度遍历
广度遍历利用队列来实现
class Queue { constructor () { this.top = 0, // 栈的长度 this.list = [] } push(item) { this.top++; this.list.push(item) // 入栈操作 } shift() { --this.top; return this.list.shift() // 出栈操作 } peek () { return this.list[this.top -1] // 查询栈顶元素 } } let treeData = { id: 0, name: '00', children: [ { id: 1, name: '01', children: [ { id: 11, name: '11', children: [] }] }, { id: 2, name: '02', children: [ { id: 22, name: '22', children: [] }] }] } function formatTreeData(data) { let queue = new Queue() queue.push(data); while(queue.top) { let item = queue.shift() for (let i in item.children) { queue.push(item.children[i]) } console.log(item.id) } } formatTreeData(treeData)