多叉樹的深度優先和廣度優先遍歷


多叉樹的深度優先和廣度優先遍歷

  • 深度優先的思想比較常見,就是使用遞歸,沒什么好說的。
  • 廣度優先的思想,主要是需要借助一個隊列,不停地將同一層級的子節點放入隊列,然后依次從隊列中取出執行。
/**
 * var Node = {
 *    data: null,
 *    children: Array<Node>
 * }
 */
function breadthFirstTraversal(node) {
    let nodeList = [node];
    while(nodeList.length > 0) {
        const current = nodeList.shift();
        console.log(current.data);
        
        if(current.children && current.children.length > 0) {
            nodeList.push(...current.children);
        }
    }
}

function depthFirstTraversal(node) {
    function traversal(node) {
        console.log(node.data);
        if(node.children && node.children.length > 0) {
            for(let i = 0;i < node.children.length;i++) {
                traversal(node.children[i]);
            }
        }
    }
    traversal(node);
}

const node = {
    data: 1,
    children: [
        {
            data: 2,
            children: [
                {
                    data: 3
                }
            ]
        },
        {
            data: 4,
            children: [
                {
                    data: 5,
                    children: [
                        {
                            data: 6
                        }
                    ]
                }
            ]
        },
        {
            data: 7
        }
    ]
}

breadthFirstTraversal(node); // 1 2 4 7 3 5 6
depthFirstTraversal(node); // 1 2 3 4 5 6 7
  • 記一次比較尷尬的面試,廣度優先寫不出來,比較憨批


免責聲明!

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



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