js數據結構處理--------樹結構數據遍歷
阿新 • • 發佈:2019-04-19
list.sh turn 處理 con pre class push 廣度遍歷 樹結構
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)
js數據結構處理--------樹結構數據遍歷