js數據結構處理--------樹結構數據遍歷


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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM