深度优先遍历

    科技2022-08-07  107

    什么是深度优先遍历

    深度优先遍历:尽可能深的搜索树的分支

    深度优先遍历算法口诀

    访问根节点; 对根节点的children挨个进行深度优先遍历。 const tree = { val: 'a', children: [ { val: 'b', children: [ { val: 'd', children: [] }, { val: 'e', children: [] } ] }, { val: 'c', children: [ { val: 'f', children: [] }, { val: 'g', children: [] } ] } ] } const dfs = (root) => { console.log(root.val); // root.children.forEach((child) => {dfs(child)}); root.children.forEach(dfs); } dfs(tree);

    运行结果:

    a b d e c f g
    Processed: 0.009, SQL: 8