首页 > 其他分享 >图文:深度优先遍历(DFS)和广度优先遍历(BFS)

图文:深度优先遍历(DFS)和广度优先遍历(BFS)

时间:2023-01-27 23:33:26浏览次数:53  
标签:优先 遍历 DFS right value null curNode left

/** * 注意:left/right值若没有显示设置为null,值即为undefined * 在调用二叉树前、中、后序遍历方法时,由于参数设置了默认值(tree) * 所以进入了死循环 */

const tree = {
    value: 5,
    left: {
        value: 3,
        left: {
            value: 2,
            left: null,
            right: null
        },
        right: {
            value: 4,
            left: null,
            right: null
        }
    },
    right: {
        value: 7,
        left: {
            value: 6,
            left: null,
            right: null
        },
        right: {
            value: 8,
            left: null,
            right: null
        }
    }
}
/** * 二叉树 * 深度优先遍历 * 使用递归与前序遍历相同 * 使用栈的方式实现 */
const depthFirstTravel = (node = tree) => {
    if(node === null) return 
    const stack = []
    stack.push(node)
    while(stack.length){
        const curNode = stack.pop()
        console.log(curNode.value)
        if(curNode.right){
            stack.push(curNode.right)
        }
        if(curNode.left){
            stack.push(curNode.left)
        }
    }
}

/**
* 二叉树
* 广度优先遍历
* 使用队列的方式实现
*/

const breadthFirstTravel = (node = tree) => {
    if(node === null) return
    const queue = []
    queue.push(node)
    while(queue.length){
        debugger
        const curNode = queue.shift()
        console.log(curNode.value)
        if(curNode.left){
            queue.push(curNode.left)
        }
        if(curNode.right){
            queue.push(curNode.right)
        }
    }
}

 

标签:优先,遍历,DFS,right,value,null,curNode,left
From: https://www.cnblogs.com/zhenjianyu/p/17069518.html

相关文章